找不到模块:无法解析"fs" - 下一页



我正在尝试将节点jsencrypt与NextJS(tsx(一起使用:

index.tsx

import JSEncrypt from 'node-jsencrypt';

软件包.json

"node-jsencrypt": "^1.0.0"

记录

错误-/node_modules/node jsencrypt/index.js:2:0

找不到模块:无法解析"fs">

注意:我没有找到'webpack.config.js'文件,正如我在某些主题中看到的那样。

好的,我试过这个问题&我想我已经涵盖了所有可能的组合。在回购中,您可以找到工作示例。有三种可能的方法,正确的方法将取决于你的项目中已经存在的内容——在最初的问题中没有具体说明的细节。

  1. 使用webpack 5next.config.js时的解决方案
module.exports = {
future: {
webpack5: true, // by default, if you customize webpack config, they switch back to version 4. 
// Looks like backward compatibility approach.
},
webpack(config) {
config.resolve.fallback = {
...config.resolve.fallback, // if you miss it, all the other options in fallback, specified
// by next.js will be dropped. Doesn't make much sense, but how it is
fs: false, // the solution
};
return config;
},
};
  1. 使用webpack 4时的解决方案-next.config.js
module.exports = {
webpack(config) { // we depend on nextjs switching to webpack 4 by default. Probably they will 
// change this behavior at some future major version.
config.node = {
fs: "empty", // webpack4 era solution 
};
return config;
},
};
  1. 您可以考虑使用其他库。根据node-jsencrypt readme,它们是jsencrypt的节点端口,这里我假设您尝试为浏览器构建。节点库停留在版本1,而原始库已经处于版本3。正如我在上次提交main时所检查的那样,如果你使用这个库,它的构建就很好,没有任何问题

原始,nextjs不知道的答案:

自版本5以来,webpack不包括用于节点库的polyfile。在您的情况下,您很可能需要将resolve.fallback.fs: false添加到您的webpack配置中。

有关此选项的详细信息-https://webpack.js.org/configuration/resolve/#resolvefallback它在v4到v6迁移指南中提到,如果您的情况是这样的话:https://webpack.js.org/migrate/5/

在next.config.js文件中添加下面的代码

build: {
extend(config, {}) {
config.node = {
fs: 'empty'
}
}

},

我在集成sendGrid时也遇到了同样的问题。然而,我通过在next.config.js文件中添加webpack属性来解决问题,如下所示:

const nextConfig = {
reactStrictMode: true,
webpack: (config) => {
config.resolve = {
...config.resolve,
fallback: {
fs: false,
},
};
return config;
},
};
module.exports = nextConfig;

最新更新