Error [ERR_REQUIRE_ESM]: How to use es6 modules in node 12?
Asked Answered
E

11

86

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
Engaging answered 23/7, 2019 at 17:58 Comment(0)
N
26

The official documentation for the module states, that v2 should be used with require().

There is a work around though. Instead being imported it can be loaded asynchronously:

const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
Natalienatalina answered 23/10, 2021 at 23:38 Comment(1)
better choose axios and save the pain...Vineyard
S
24

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 "
Squier answered 23/9, 2019 at 2:19 Comment(4)
This is not correct. Doesn't work with nodejs version 12 LTS and no mention of --experimental-modules in the nodejs documentation for version 12 or 14. I think this option was a feature in development that was removed.Ocher
Yes, was a feature before nodejs v12.00 as per this article medium.com/@nodejs/…Squier
Worked for me with version 12.16.1, IDK why it did not work for you @OcherSalangia
import Jimp from 'jimp'; Was causing the same issue, import('jimp').then((jimp) => jimp.read(fileBuffer)) Thank you so much, you saved my dayFrolic
M
20

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... :(

Maidservant answered 26/9, 2020 at 12:2 Comment(0)
S
4

Solved use https://www.npmjs.com/package/nanoid-esm

import nanoid from 'nanoid-esm';
console.log(nanoid())
Soldo answered 3/10, 2022 at 18:49 Comment(1)
Resolved as const nanoid = require('nanoid-esm');. Thanks.Frieda
N
3

You have to add this line of code in your package.json file "type" : "module" You will be able to use imports statements instead of require if I get your question correctly.

Your package.json will look as follows:

{
  "name": "dynamic-es6-mod",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.mjs",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node src/index.mjs"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "globby": "^10.0.1"
  }
}
Nesline answered 7/9, 2020 at 10:9 Comment(1)
too bad this breaks all other require statements...Christman
P
2

I had a hell of a time with all this. I'm just posting my solution repo, in hopes it helps someone else.

This imports an ESM dependency (ora) into TypeScript without using babel. https://github.com/jason-henriksen/typescript-with-esm-no-babel-boilerplate

Passing answered 5/12, 2021 at 6:10 Comment(1)
Hi, I think I am going through what you went through. I am unable to understand your solution. Can you please elaborate further please? Also, I haven't cloned your repo yet. Does that explains the solution?Strickler
H
2
  1. Go to package.json file and write "type":"module", above debug like this:
"name": "npmmodule",
"version": "1.0.0",
"main": "index.js",
"type": "module",
  1. Use import instead of require:
import chalk from 'chalk';

console.log(chalk.blue("hello world"));
Hayleyhayloft answered 1/6, 2022 at 9:35 Comment(1)
Doesn't work for file-typeAnosmia
S
-1

Use previous or older version of your installed node module. It will work.

Stubblefield answered 8/5, 2022 at 17:51 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Caryophyllaceous
Always nice to provide some additional details for an actual answer. It's a very generic answer and is more of a comment than a solution.Inquire
H
-3

For Node.js:

Tell Node to ignore the error.

const Module = require('module')
const orig = Module._extensions['.js']
const fs = require('fs')
Module._extensions['.js'] = function (module, filename) {
  try {
    return orig(module, filename)
  } catch (e) {
    if (e.code === 'ERR_REQUIRE_ESM') {
      // From: https://github.com/nodejs/node/blob/c24b74a7abec0848484671771d250cfd961f128e/lib/internal/modules/cjs/loader.js#L1237-L1238
      const content = fs.readFileSync(filename, 'utf8')
      module._compile(content, filename)
      // --
      return
    }
    throw e
  }
}

Use Babel to transpile on-the-fly.

require('@babel/register', {
  ignore: (f) => {
    // Don't ignore the package we want to transpile.
    if (f.match('semver-regex') return false
    // Prevent babel transpiling anything else in `node_modules`.
    return f.match('node_modules')
  },
  overrides: [{
    // Set preset to be used to transpile our ESM package.
    test: /semver\-regex/,
    presets: ['es2015'],
  }]
})

// Call the rest of your code.
require('./index.js')

For Webpack:

Do similar but with Babel loaders and without the Node require hook.

Hypolimnion answered 10/5, 2021 at 21:18 Comment(0)
E
-4

Try using npm's esm module which will support es6 (It can also be used in production).

Ember answered 17/6, 2020 at 10:20 Comment(1)
Can you elaborate,please!Parapsychology
D
-6

Just need to update node:

run: nvm install 15 nvm use 15

credit: https://www.youtube.com/watch?v=sUkCszM2gvU https://www.youtube.com/watch?v=sUkCszM2gvU

Doubleheader answered 13/7, 2021 at 6:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.