gpt4 book ai didi

javascript - 在 Next.js ERR_REQUIRE_ESM 中导入 ES 模块

转载 作者:行者123 更新时间:2023-12-03 16:31:48 27 4
gpt4 key购买 nike

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

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


我认为问题在于 Webpack(或 Babel)正在改变所有 import转至 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 库有 "type": "module"在其package.json .使用 next-transpile-modules不再需要转译 ESM 库。

Next.js 12 之前
由于ky导出为 ESM,您可以使用 next-transpile-modules 对其进行转换在 next.config.js .

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

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

关于javascript - 在 Next.js ERR_REQUIRE_ESM 中导入 ES 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65974337/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com