在Node 中运行ESM

34 阅读1分钟

在Node环境中运行ESM,有三种方式:

  1. 文件名后缀为 .mjs;
  2. 文件名后缀为 .js,且package.json 的type指定为 "module";
  3. 命令中加上 --input-type=module
// 01.js
import fs from 'fs';
console.log(fs);

方式1:修改01.js 为 01.mjs

$ node 01.mjs

image.png

方式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"
}

image.png

方式3:直接在命令行输入脚本内容并与运行

例如:node --input-type=module --eval "import * as a from 'path'; console.log(a);"

image.png