Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Import error when using next.js #336

Closed
vedantroy opened this issue May 3, 2021 · 2 comments
Closed

Import error when using next.js #336

vedantroy opened this issue May 3, 2021 · 2 comments

Comments

@vedantroy
Copy link

When I try to import this library with import ky from 'ky' inside next.js, I get the following error:

Error: Must use import to load ES Module: /home/vedantroy/Desktop/projects/slate/node_modules/ky/index.js
require() of ES modules is not supported.
require() of /home/vedantroy/Desktop/projects/slate/node_modules/ky/index.js from /home/vedantroy/Desktop/projects/slate/.next/server/pages/index.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 /home/vedantroy/Desktop/projects/slate/node_modules/ky/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/vedantroy/Desktop/projects/slate/node_modules/ky/package.json.
@sholladay
Copy link
Collaborator

sholladay commented May 3, 2021

That is a problem with Next.js. Behind the scenes, it is transforming your import statement to use require(), and that's incorrect in this case because Node doesn't allow require()ing an ES module. Ky just happens to be one of the first few popular packages on npm that is distributed in ES module format. Going forward, ES modules are going to become the norm, so this is really something that needs to be fixed in Next.js. I strongly recommend commenting on vercel/next.js#23725 or opening a new issue on the Next.js issue tracker to bring more attention to it.

In the meantime, there are workarounds that exist. You can use next-transpile-modules to transpile Ky, or you can use Ky v0.25 or below, which includes a UMD build that is fully compatible with require() and Next.js. Personally, I would recommend just using Ky v0.25, as it's pretty similar to the latest v0.27, and that's a more natural solution with less complexity.

See also:

@gaurav5430
Copy link

can we not use webpack babel-loader to transpile instead of next-transpile-modules ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants