【问题标题】:Module not found: Can't resolve 'fs' - NextJS找不到模块:无法解析“fs”-NextJS
【发布时间】:2021-08-01 08:02:01
【问题描述】:

我正在尝试将 node-jsencrypt 与 NextJS (tsx) 一起使用:

index.tsx

import JSEncrypt from 'node-jsencrypt';

package.json

"node-jsencrypt": "^1.0.0"

日志

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

找不到模块:无法解析“fs”

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

【问题讨论】:

标签: reactjs webpack next.js


【解决方案1】:

好的,我解决了这个问题,我想我已经掌握了所有可能的组合。在repo 中,您可以找到工作示例。有 3 种可能的方法,正确的方法取决于您的项目中已有的内容 - 原始问题中未指定的详细信息。

  1. 使用 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;
  },
};
  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 版。正如我在the last commit on 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/

【讨论】:

    【解决方案2】:

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

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

    },

    【讨论】:

    • 我用的是next.config.js,你知道怎么加吗?
    • 我的意思是 next.config.js 不是 nuxt.config.js
    • 好的,只需在根目录添加 next.config.js 即可。然后添加 module.exports = {build: { extend(config, {}) { config.node = { fs: 'empty' } }}
    猜你喜欢
    • 2022-06-27
    • 1970-01-01
    • 2018-06-29
    • 2022-08-05
    • 2019-12-01
    • 2019-05-31
    • 2020-02-24
    • 2021-10-20
    相关资源
    最近更新 更多