在 Next.js 中导入 ES 模块 ERR_REQUIRE_ESM

Cam*_*ilo 10 javascript webpack babeljs es6-modules next.js

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

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

我认为问题在于 Webpack(或 Babel)正在将所有imports转换为require()s 但它ky是一个纯 ES 模块。

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

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

  const response = await ky
    .get('http://localhost/api/foo')
    .json();
};
Run Code Online (Sandbox Code Playgroud)

有什么建议?

jul*_*ves 20

由于ky是作为 ESM 导出的,因此您可以使用next-transpile-modulesin进行转译next.config.js。

// next.config.js
const withTM = require('next-transpile-modules')(['ky']);

module.exports = withTM(/* your Next.js config */);
Run Code Online (Sandbox Code Playgroud)


Ada*_*nko 5

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

请参阅: https: //github.com/vercel/next.js/pull/27069

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