在Node环境中运行ESM,有三种方式:
- 文件名后缀为 .mjs;
- 文件名后缀为 .js,且package.json 的type指定为 "module";
- 命令中加上 --input-type=module
// 01.js
import fs from 'fs';
console.log(fs);
方式1:修改01.js 为 01.mjs
$ node 01.mjs
方式2:package.json 添加 type:module
$ node 01.js
{
"name": "modules",
"version": "1.0.0",
"description": "",
"main": "index.js",
+ "type": "module",
"scripts": {
"start": " "
},
"keywords": [],
"author": "",
"license": "ISC"
}
方式3:直接在命令行输入脚本内容并与运行
例如:node --input-type=module --eval "import * as a from 'path'; console.log(a);"