找不到模块:无法解析“fs"-NextJS [英] Module not found: Can't resolve 'fs' - NextJS
问题描述
我正在尝试将 node-jsencrypt 与 NextJS (tsx) 一起使用:
I'm trying to use node-jsencrypt with NextJS (tsx):
index.tsx
import JSEncrypt from 'node-jsencrypt';
package.json
package.json
"node-jsencrypt": "^1.0.0"
日志
错误 - ./node_modules/node-jsencrypt/index.js:2:0
error - ./node_modules/node-jsencrypt/index.js:2:0
找不到模块:无法解析fs"
Module not found: Can't resolve 'fs'
注意事项:正如我在某些主题中看到的那样,我没有找到 'webpack.config.js'
文件.
Notes:
I didn't find the 'webpack.config.js'
file, as I saw in some topics.
推荐答案
好的,我解决了这个问题 &我想我已经涵盖了所有可能的组合.在 repo 你可以找到工作示例.有 3 种可能的方法,正确的方法取决于您的项目中已有的内容 - 原始问题中未指定的详细信息.
Ok, I played around with this issue & I think I have what cover all possible combinations. In the repo you can find working examples. There are 3 possible approaches, and the right one will depend on what's already in your project - details that were unspecified in the original question.
- 使用 webpack 5 时的解决方案
next.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;
},
};
- 使用 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;
},
};
- 您可以考虑使用其他库.根据
node-jsencrypt readme
他们是节点端口jsencrypt,在这里我假设您尝试为浏览器构建.节点库卡在版本 1,而原始库已经在版本 3.正如我在 main 上的最后一次提交,如果你使用这个库,它构建得很好,没有任何问题.
- You could consider using other library. According to
node-jsencrypt readme
they are node port of jsencrypt, and here I assume you try to build for browser. The node library got stuck at version 1, while the original library is already at version 3. As I checked in the last commit on main, if you use this library, it's building just fine without any issues.
原创,nextjs 不知道答案:
从版本 5 开始,webpack 不再包含节点库的 polyfile.在您的情况下,您很可能需要将 resolve.fallback.fs: false
添加到您的 webpack 配置中.
Since version 5, webpack doesn't include polyfiles for node libraries. In your case, you most likely need to add resolve.fallback.fs: false
to your webpack config.
有关此选项的更多信息 - https://webpack.js.org/configuration/resolve/#resolvefallback它在 v4 到 v6 迁移指南中提到,如果这是您的情况:https://webpack.js.org/migrate/5/
More about this option- https://webpack.js.org/configuration/resolve/#resolvefallback It mentioned in v4 to v6 migration guide, if this is your case: https://webpack.js.org/migrate/5/
这篇关于找不到模块:无法解析“fs"-NextJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!