Using Es Modules In Node.js 12 In A Nutshell
ESM (ECMAScript Module) 在 Node.js 12 中已经处于第二阶段(试验中),通过额外参数即可使用其提供的语法。
- 传入参数
--experimental-modules, 或--input-type=module。 - 确保文件使用文件扩展名
.mjs, 如果仍使用旧有的.js文件扩展名则需要在package.json中添加属性"type": "module"。 import语句中也要在被导入文件后添加.mjs,因为 ESM 不会自动添加文件扩展名,例如,import bar from './bar.mjs'.
注意:
- 目前(截止 Node.js 12.7.0 为止)还不支持导入文件夹。
- CommonJS 与 ESM 之间的互操作性还不完美,需要额外工作。
- ESM 不存在变量
__filename和__dirname,使用import.meta.url。
参考:
- ECMAScript Modules | Node.js 12 Documentation
- Announcing a new –experimental-modules
- The new ECMAScript module support in Node.js 12
- PR on ESM implementation
ESM (ECMAScript Module) is now phase 2 (Experimental) in Node.js 12 and can be activated with optional flag.
- Enabling
--experimental-modulesflag, or--input-type=modulefor input via stdin. - Files ending in
.mjs, or.jswith adding"type": "module"to the nearestpackage.jsonfile. - Explicitly add
.mjsin theimportstatements, because ESM doesn’t add missing filename extensions, e.g,import bar from './bar.mjs'.
Caveat:
- Currently (as for Node.js 12.7.0) importing directories is not supported.
- Interoperability between CommonJS and ESM is still not perfect, extra work needed.
__filenameand__dirnameare not available in ESM, useimport.meta.urlinstead.