27

I came upon this error when trying to use ky in a Next.js project:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /foo/node_modules/ky/index.js

I think the problem is that Webpack (or Babel) is transforming all imports to require()s but ky is a pure ES module.

I got it working by dynamically importing ky before using it but it's not elegant nor efficient.

const handleFormSubmit = async (event) => { const ky = (await import("ky")).default; const response = await ky .get('http://localhost/api/foo') .json(); }; 

Any suggestions?

4 Answers 4

38

From Next.js 12, support for ES Modules is now enabled by default, as long as the ESM library has "type": "module" in its package.json. Using next-transpile-modules to transpile ESM libraries is no longer required.


Before Next.js 12

Since ky is exported as ESM you can transpile it with next-transpile-modules in next.config.js.

// next.config.js const withTM = require('next-transpile-modules')(['ky']); module.exports = withTM(/* your Next.js config */); 
Sign up to request clarification or add additional context in comments.

6 Comments

I had this same problem trying to use unist-util-visit @3.1.0. This is the right answer. Thanks!
I also faced a similar issue with three.js and this solved my problem. Additional link that helped w/ my issue: website-git-switcher-pmndrs.vercel.app/react-three-fiber/…
In Next.js 12 I still hit this issue with the following build command esbuild index.ts --outdir=dist --sourcemap --bundle --minify --platform=neutral --main-fields=module,main,browser It builds as ESM, but then importing my module in _app.js stills throws this error
@EricBurel Do you have "type": "module" in the lib's package.json?
Yep. I'll build a repro/demo here: github.com/VulcanJS/npm-the-right-way, I've started to document our build process for full stack packages and compare technologies. I've tried with Next 12 but Webpack 4 only so maybe that's related.
|
5

You can try upgrading nextjs to v11.1.0, it has some support for ESM.

See: https://github.com/vercel/next.js/pull/27069

More info in this issue discussion from https://github.com/vercel/next.js/issues/9607#issuecomment-906155992

1 Comment

That's really neat!
3

Since Next.js 12 (official announcement), support for ESM modules is automatically enabled. See #29878.

Since Next.js 12.1, you can add "type": "module" to your package.json. See #33637.

Comments

0

NextJS 12 (and maybe 13?) and TypeScript: please see this link, then add --esm to your "dev" line in your main package.json as this user suggests here, and finally, update (or make sure) your tsconfig.server.json (inherits from tsconfig.json) says "module": "ESNext" instead of "module": "commonjs".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.