如何在Webpack 5中填充节点核心模块

时间:2020-10-27 15:25:15

标签: node.js webpack

webpack 5不再对节点核心模块进行自动填充。 请如何解决? PS:我是开发的初学者,因此必须向我详细说明解决方案。

errors

7 个答案:

答案 0 :(得分:22)

使用 node-polyfill-webpack-plugin 读取对 Node.js 核心模块的支持:

安装软件包后,将以下内容添加到您的 webpack.config.js:

const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")

module.exports = {
    // Other rules...
    plugins: [
        new NodePolyfillPlugin()
    ]
}

答案 1 :(得分:17)

我认为这里的大多数答案都可以解决您的问题。但是,如果您的节点开发不需要 Polyfill,那么我建议您在 Webpack 模块配置中使用 target: 'node'。这帮助我解决了这个问题。

以下是有关答案的一些文档:https://webpack.js.org/concepts/targets/

enter image description here

答案 2 :(得分:12)

看起来您使用了默认情况下未包含在 webpack 构建中的 // this script must be loaded BEFORE the script at vuln.com/displaysensitivedata Object.defineProperty(document, 'domain', {get: () => "vuln.com"}); function displaysensitiveinfo(data) { alert(`gotcha ${data}`); } // vuln.com/displaysensitivedata (function (sensitivedata) { if (document.domain === 'vuln.com') { displaysensitiveinfo(sensitivedata); } })([['data1', 'FLAG{}']]); 包。对我来说,像这样扩展 webpack 配置有帮助:

path

如果您使用纱线,还可以通过 { // rest of the webpack config resolve: { // ... rest of the resolve config fallback: { "path": require.resolve("path-browserify") } }, } path-browserify 安装 npm install path-browserify --save-dev

答案 3 :(得分:3)

当我重新安装节点模块时,我的 webpack 当前版本是 5.38.1,我已经解决了这个问题 npm i path-browserify -D 安装后,您必须更新您的 webpack.config.js resolve{} fallback: {"fs": false, "path": require.resolve("path-browserify")} 在不使用 "fs": false 时显示错误,即:Module not found: Error: Can't resolve 'fs' in '/YOUR DIRECTORY ...' 所以不要忘记添加它;与其他东西看起来像:

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

删除 node 属性(如果它存在于您的 webpack.config.js 文件中)

答案 4 :(得分:2)

从webpac v4升级到v5时,我也遇到了这些错误。 解决

添加了resolve.fallback属性

已删除节点属性

{
resolve: {
  modules: [...],
  fallback: {
    "fs": false,
    "tls": false,
    "net": false,
    "path": false,
    "zlib": false,
    "http": false,
    "https": false,
    "stream": false,
    "crypto": false,
    "crypto-browserify": false,
  }
},
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

答案 5 :(得分:0)

npm install path-browserify 然后尝试将webpack配置更改为包括以下内容:

module.exports = {
    ...
    resolve: {
        alias: {
            path: require.resolve("path-browserify")
        }
    }
};

答案 6 :(得分:-2)

你想在 const nodeExternals = require('webpack-node-externals'); 中使用

在 webpack.config.js 中添加 target: "node", 开发工具:“源地图”, 外部:[nodeExternals()],

我认为它的帮助很大