繁体   English   中英

在 Next.js ERR_REQUIRE_ESM 中导入 ES 模块

[英]Import ES module in Next.js ERR_REQUIRE_ESM

我在 Next.js 项目中尝试使用ky时遇到了这个错误:

错误 [ERR_REQUIRE_ESM]: 必须使用 import 来加载 ES 模块:/foo/node_modules/ky/index.js

我认为问题在于 Webpack (或 Babel)正在将所有import转换为require() ,但ky是纯 ES 模块

我通过在使用它之前动态导入ky来让它工作,但它既不优雅也不高效。

const handleFormSubmit = async (event) => {
  const ky = (await import("ky")).default;

  const response = await ky
    .get('http://localhost/api/foo')
    .json();
};

有什么建议么?

由于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 */);

您可以尝试将 nextjs 升级到 v11.1.0,它对 ESM 有一些支持。

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

此问题讨论中的更多信息来自https://github.com/vercel/next.js/issues/9607#issuecomment-906155992

自 Next.js 12 起,自动启用对 ESM 模块的支持。 请参阅#29878

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM