在 Next.js ERR_REQUIRE_ESM 中导入 ES 模块

Import ES module in Next.js ERR_REQUIRE_ESM

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

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

我认为问题在于 Webpack(或 Babel)正在将所有 imports 转换为 require()s 但 ky is a pure ES module.

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

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

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

有什么建议吗?

从 Next.js 12 开始,现在默认启用 support for ES Modules,只要 ESM 库的 package.json 中有 "type": "module"。不再需要使用 next-transpile-modules 转译 ESM 库。


之前 Next.js 12

由于 ky 导出为 ESM,您可以在 next.config.js.

中使用 next-transpile-modules 转译它
// 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 (official announcement), support for ESM modules is automatically enabled. See #29878.

从 Next.js 12.1 开始,您可以将 "type": "module" 添加到您的 package.json。参见 #33637