Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 568
Armeen Harwood Avatar asked Jul 23 '19 17:07

Armeen Harwood


People also ask

Does Node 12 support ES6?

Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from 'express' node js will throw an error as follows: Node has experimental support for ES modules.

How do you solve require () of ES modules is not supported?

You can solve the "[ERR_REQUIRE_ESM]: require() not supported" by doing one of two things: Use ESM - use import foo from 'foo' , instead of const foo = require('foo') and add the following line to your package. json file: "type": "module" . Downgrade to the last version of the package that is built with CommonJS .

How do I use ECMAScript modules in Node?

Authors can tell Node. js to use the ECMAScript modules loader via the . mjs file extension, the package. json "type" field, or the --input-type flag.


2 Answers

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 " 
like image 182
abdulrahman alaa Avatar answered Sep 19 '22 16:09

abdulrahman alaa


In Node 14 I solved it with workaround.

source of workaround: https://github.com/eslint/eslint/issues/12319#issuecomment-535799024

short summary:

  1. your root level package.json doesn't support ESM
  2. subdirectory does - in src directory place package.json with { "type": "module" }

PS: ESLint team can't solve it easily right now, just because of core design... :(

like image 34
Michal Miky Jankovský Avatar answered Sep 19 '22 16:09

Michal Miky Jankovský