[英]Import ES module in Next.js ERR_REQUIRE_ESM
I came upon this error when trying to use ky
in a Next.js project:我在 Next.js 项目中尝试使用
ky
时遇到了这个错误:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /foo/node_modules/ky/index.js
错误 [ERR_REQUIRE_ESM]: 必须使用 import 来加载 ES 模块:/foo/node_modules/ky/index.js
I think the problem is that Webpack (or Babel) is transforming all import
s to require()
s but ky
is a pure ES module .我认为问题在于 Webpack (或 Babel)正在将所有
import
转换为require()
,但ky
是纯 ES 模块。
I got it working by dynamically importing ky
before using it but it's not elegant nor efficient.我通过在使用它之前动态导入
ky
来让它工作,但它既不优雅也不高效。
const handleFormSubmit = async (event) => {
const ky = (await import("ky")).default;
const response = await ky
.get('http://localhost/api/foo')
.json();
};
Any suggestions?有什么建议么?
Since ky
is exported as ESM you can transpile it with next-transpile-modules
in next.config.js
.由于
ky
被导出为 ESM,您可以在 next.config.js 中使用next-transpile-modules
对其进行next.config.js
。
// next.config.js
const withTM = require('next-transpile-modules')(['ky']);
module.exports = withTM(/* your Next.js config */);
You can try upgrading nextjs to v11.1.0, it has some support for ESM.您可以尝试将 nextjs 升级到 v11.1.0,它对 ESM 有一些支持。
See: https://github.com/vercel/next.js/pull/27069见: 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此问题讨论中的更多信息来自https://github.com/vercel/next.js/issues/9607#issuecomment-906155992
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.