使用ES6模块时提示Must use import to load ES Module

7,445 阅读1分钟

问题描述

模块中的内容如下:

//module1.mjs中的文件
export const PI=3.1415926;

//module2.mjs中的文件
import {PI} from "./module1.mjs";
console.log(PI);

当运行module2.mjs时会报错: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: module2.mjs

解决方法

运行时加入参数 --experimental-modules

node --experimental-modules module2.mjs

扩展

Since Node 13, you can use either the .mjs extension or set "type": "module" in your package.json. You don't need to use the --experimental-modules flag.

Since Node 12, you can use either the .mjs extension or set "type": "module" in your package.json. And you need to run node with the --experimental-modules flag.

In Node 9, it is enabled behind a flag, and uses the .mjs extension. node --experimental-modules my-app.mjs