在 Next.js ERR_REQUIRE_ESM 中导入 ES 模块 [英] Import ES module in Next.js ERR_REQUIRE_ESM

查看:188
本文介绍了在 Next.js ERR_REQUIRE_ESM 中导入 ES 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I came upon this error when trying to use ky in a Next.js project:

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

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

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

I think the problem is that Webpack (or Babel) is transforming all imports to require()s but ky is a pure ES module.

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

I got it working by dynamically importing ky before using it but it's not elegant nor efficient.

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

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

有什么建议吗?

推荐答案

从 Next.js 12,对 ES 模块的支持 现在默认启用,只要 ESM 库在其 "type": "module"代码>package.json.不再需要使用 next-transpile-modules 转译 ESM 库.

From Next.js 12, support for ES Modules is now enabled by default, as long as the ESM library has "type": "module" in its package.json. Using next-transpile-modules to transpile ESM libraries is no longer required.

由于 ky 被导出为 ESM,您可以使用 next-transpile-modulesnext.config.js.

Since ky is exported as ESM you can transpile it with next-transpile-modules in next.config.js.

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

module.exports = withTM(/* your Next.js config */);

这篇关于在 Next.js ERR_REQUIRE_ESM 中导入 ES 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆