在Node.js中启用ECMAScript模块

我正在尝试在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 };
sax110 回答:在Node.js中启用ECMAScript模块

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

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

导入默认导出

因此,如果将myFunction导出为import myFunction from './module.js';

,则export default myFunction;将起作用
本文链接:https://www.f2er.com/2751258.html

大家都在问