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
- Create a new Nuxt project.
npm i hast-util-selectto 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).- Create a file
~/plugins/test.jswith the following code:
import { select } from "hast-util-select";
console.log("test", select("p", {
type: "element",
tagName: "p",
properties: {},
children: [],
}));
- 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
- fix require vs import of ES module error see https://github.com/nuxt/nuxt/issues/9223#issuecomment-840747064 — committed to beeldengeluid/labs.beeldengeluid.nl by phivk a year ago
Adding esmodule dependencies (and their dependnecies) to
build.transpileis a good idea.Alternatively, you can use
build.standalone: trueinnuxt.configfile. (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:
👍 for the
build.standalone: truesolution. 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