Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

javascript - Error [ERR_REQUIRE_ESM]: How to use es6 modules in node 12?

From https://2ality.com/2019/04/nodejs-esm-impl.html Node 12 should support es6 modules; however, I just keep getting the error:

Question: How do I make a MVP of using es6 modules in node 12?

package.json

{
  "name": "dynamic-es6-mod",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.mjs",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "node src/index.mjs"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "globby": "^10.0.1"
  }
}
$ node -v
$ 12.6.0
$ npm run start


internal/modules/cjs/loader.js:821
  throw new ERR_REQUIRE_ESM(filename);
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/dev/dynamic-es6-mod/src/index.mjs
    at Object.Module._extensions..mjs (internal/modules/cjs/loader.js:821:9)
    at Module.load (internal/modules/cjs/loader.js:643:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:839:10)
    at internal/main/run_main_module.js:17:11
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All you have to do is adding the flag --experimental-modules that supports the new es6 import/export statement also the order is important as the following.

    "start": "node --experimental-modules src/index.mjs "

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...