Webpack 5不再对节点核心模块进行自动填充。 请问怎么修?

break CHANGE:默认情况下,webpack < 5用于为node.js核心模块包含polyfills。 现在情况已经不同了。验证你是否需要这个模块,并为它配置一个填充。


当前回答

我正在使用craco的create-react-app,在升级到webpack 5时遇到了以下错误:

“缓冲”


Module not found: Error: Can't resolve 'buffer' in '/Users/therightstuff/my-project/node_modules/safe-buffer'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
    - install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "buffer": false }

这个问题通过安装npm install -D buffer来解决。

'fs'


Module not found: Error: Can't resolve 'fs' in '/Users/therightstuff/my-project/node_modules/line-navigator'

这个问题通过在craco配置craco.config.js中设置webpack回退来解决:

module.exports = {
    style: {
        postcssOptions: {
            plugins: [
            require('tailwindcss'),
            require('autoprefixer'),
            ],
        },
    },
    webpack: {
        configure: (webpackConfig, { env, paths }) => {
            // eslint-disable-next-line no-param-reassign
            webpackConfig.resolve.fallback = {
                fs: false,
            };
            return webpackConfig;
        },
    },
}

其他回答

错误:[webpack < 5用于默认包含node.js核心模块的腻子。

现在情况已经不同了。验证你是否需要这个模块,并为它配置一个填充。

答: Node_modules > react-scripts > config > webpack.config.js

在webpack.config.js文件中添加:

resolve: {
      fallback: { 
        "http": require.resolve("stream-http") ,
         "path": require.resolve("path-browserify") 
        },
}

所有其他答案都遗漏了一个重要的部分:如何不填充节点核心模块。 如果错误来自你的依赖项的依赖项中的某个模块,而你实际上并不需要,你可以完全忽略它。 在这种情况下,最简单的解决方法是添加到包中。Json这些行:

"browser": {
  "fs": false,
  "path": false,
  "os": false
}

如果需要忽略其他核心节点模块,也可以这样做。

这种方法适用于默认情况下实际webpack配置不能直接访问的框架(比如Angular)。

在寻找不同的错误时,我已经找到了这个解决方案。

当我重新安装节点模块时,我的webpack当前版本是5.38.1,我已经修复了这个问题 安装后,你必须更新你的webpack.config.js resolve{} with 回退:{"fs": false, "path": require.resolve("path-browserify")}而不使用"fs": false它显示错误,即:模块未找到:错误:无法解析'fs'在'/YOUR DIRECTORY…' 所以别忘了加上它;与其他东西看起来像:

module.exports = {
   ...
   resolve: {
    extensions: [".js", ".jsx", ".json", ".ts", ".tsx"],// other stuff
    fallback: {
      "fs": false,
      "path": require.resolve("path-browserify")
    }
  },
};

如果你的webpack.config.js文件中存在node属性,删除它

我找到了一个适合我的解决方案:

卸载webpack 删除“package-lock”。json”文件 NPM安装webpack@4.44.2——force 包括在“套餐”中。Json”文件在你的“脚本”: "脚本":{ "start": "SET NODE_OPTIONS=——openssl-legacy-provider && react-scripts start", "SET NODE_OPTIONS=——openssl-legacy-provider && react-scripts build", “test”:“react-scripts test”, "eject": "react-scripts eject" }

面对同样的问题,这里有一个解决方案:

删除package-lock。Json从项目文件夹和NPM卸载webpack 将react-script从5降级为4.0.3 确保包锁。Json被删除/删除 使用npm Install webpack@4.44.2安装webpack 最后,使用终端运行npm install