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

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

问题描述

我在尝试使用 ky 时遇到了这个错误Next.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();
};

有什么建议吗?

推荐答案

由于 ky 是作为 ESM 导出的,您可以在 next-transpile-modules 中对其进行转译>next.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 中导入 ES 模块 ERR_REQUIRE_ESM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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