nuxt: Error: "Must use import to load ES Module", but I'm already using `import`!

Versions

  • nuxt: v2.15.4
  • node: v14

Reproduction

https://codesandbox.io/s/wizardly-rgb-8jpy8?file=/plugins/test.js

Steps to reproduce

  1. Create a new Nuxt project.
  2. npm i hast-util-select to install the particular library I’m having trouble with (which by the way is part of a widely used ecosystem and work fine outside of Nuxt, so I’m pretty confident it’s not the problem here).
  3. Create a file ~/plugins/test.js with the following code:
import { select } from "hast-util-select";

console.log("test", select("p", {
  type: "element",
  tagName: "p",
  properties: {},
  children: [],
}));
  1. Add the plugin to nuxt.config.js.

What is Expected?

The project runs without errors.

What is actually happening?

The error…

Must use import to load ES Module: /sandbox/node_modules/hast-util-select/index.js require() of ES modules is not supported. require() of /sandbox/node_modules/hast-util-select/index.js from /sandbox/node_modules/vue-server-renderer/build.dev.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /sandbox/node_modules/hast-util-select/package.json.

…is shown on the front-end.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 19
  • Comments: 15 (1 by maintainers)

Commits related to this issue

Most upvoted comments

Adding esmodule dependencies (and their dependnecies) to build.transpile is a good idea.

Alternatively, you can use build.standalone: true in nuxt.config file. (see sandbox fork)

With either workaround, we avoid externalizing server bundle dependencies (nuxt2 uses CommonJS for building server and by default externalizes all node_modules. Which is why broken with new type of packages that are esm only.)

Since this kind of packages are getting more common in npm ecosystem, I think we might make a fork of webpack-node-externals that has continuous of package exports type, automatically inlining esmodules.

Hey @AaronBeaudoin I ran into this today and was able to solve it by updating my nuxt.config.js build config to have it transpile the ESM packages like so:

// nuxt.config.js
  build: {
    transpile: [
      '@sindresorhus/slugify',
      '@sindresorhus/transliterate',
      'hast-util-select',
    ],
  }

👍 for the build.standalone: true solution. I experienced this issue with d3 dependencies. Because d3 packages are using other d3 package as dependencies I would have to transpile every dependency.

Adding build.standalone: true, did it for me! Thanks a million @pi0