我正在尝试在Node.js 12中使用ECMAScript模块,但是我正在努力。只需在official docs之后加上顶级字段“ type”,并将其值添加为“ module” ,就足以在该节点中继续使用扩展名.js
。 js版本,但我找不到为什么无法正常工作。我想念什么吗?
$ node --version
v12.14.1
$ cat package.json
{
"type": "module","scripts": {
"start": "node test.js"
}
}
$ npm start
> app@ start /usr/src/app
> node test.js
/usr/src/app/test.js:1
import { myFunction } from './module.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Module._compile (internal/modules/cjs/loader.js:891:18)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runmain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11
$ cat test.js
import { myFunction } from './module.js';
myFunction();
$ cat module.js
function myFunction() {
console.log('hello from module');
}
export { myFunction };