在 Node.js 中启用 ECMAScript 模块



我正在 Node.js 12 中试验 ECMAScript 模块,但我正在努力。遵循官方文档,只需添加值为"模块"的顶级字段"type">就足以继续使用此 Node.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 };

https://nodejs.org/docs/latest-v12.x/api/esm.html#esm_code_import_code_statements

该导入语句的版本 12 文档显示您只能通过import ... from ...导入默认导出

因此,如果您将myFunction导出为export default myFunction;import myFunction from './module.js';将起作用

相关内容

最新更新