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

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


当前回答

当我重新安装节点模块时,我的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属性,删除它

其他回答

你想用在

const nodeExternals = require('webpack-node-externals');

在webpack.config.js中添加

target: "node",
devtool: "source-map",
externals: [nodeExternals()],

看起来你已经使用了默认情况下不包含在webpack构建中的path包。对我来说,像这样扩展webpack配置有帮助:

{
  // rest of the webpack config
  resolve: {
    // ... rest of the resolve config
    fallback: {
      "path": require.resolve("path-browserify")
    }
  },
}

也可以通过npm install path-browserify——save-dev或yarn添加path-browserify——dev来安装path-browserify。

npm install assert --save

npm install buffer --save

对于任何面临类似问题的人,只需安装缺少的模块。这些模块被报告为缺失,因为它们是node.js的一部分,但也可以通过npm单独使用。

当从webpack v4升级到v5时,我也得到了这些错误。 通过对webpack.config.js进行以下更改来解决

添加的决心。回退财产

删除节点属性

{
resolve: {
  modules: [...],
  fallback: {
    "fs": false,
    "tls": false,
    "net": false,
    "path": false,
    "zlib": false,
    "http": false,
    "https": false,
    "stream": false,
    "crypto": false,
    "crypto-browserify": require.resolve('crypto-browserify'), //if you want to use this module also don't forget npm i crypto-browserify 
  } 
},
entry: [...],
output: {...},
module: {
  rules: [...]
},
plugins: [...],
optimization: {
  minimizer: [...],
},
// node: {
//   fs: 'empty',
//   net: 'empty',
//   tls: 'empty'
// },
}

从v4升级到v5 => https://webpack.js.org/migrate/5/#clean-up-configuration

我从express导入路由器时得到这个错误 import {Router} from 'express';

修正后解决 import {Router} from '@angular/ Router ';