【发布时间】:2021-05-21 16:39:28
【问题描述】:
Webpack 无法解析核心 Node.js 模块
我知道这不是这里唯一与 Webpack 相关的 Node.js 模块查询,但是当应用我在其他地方读到的解决方案时,另一个核心模块似乎正在导致另一个 ReferenceError。
我有一个 index.js 文件,它需要 Crypto module 将哈希记录到控制台:
index.js
const crypto = require('crypto')
const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
.update('I love cupcakes')
.digest('hex');
console.log(hash);
在设置我的 webpack.congif.js 文件时,我得到了这个错误:
重大变化:webpack
- 添加回退 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
- 安装“加密浏览器”
遵循上述指导后,我在“buffer”和“stream”模块中遇到了同样的错误,为了编译配置文件,我添加了回退语句并安装了相关模块以覆盖这些缺失的依赖项:
webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
node: {
global: true,
},
resolve: {
fallback: {
"crypto": require.resolve("crypto-browserify"),
"buffer": require.resolve("buffer/"),
"stream": require.resolve("stream-browserify")
}
},
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
};
Webpack.config 现在可以编译,但是当我在浏览器中运行 index.html 时,我在浏览器控制台中收到以下错误:
未捕获的引用错误:未定义进程
正如 'Breaking Change' 错误中所述,Webpack 5 不再为节点核心模块添加 polyfill,但这是否意味着每个节点模块都需要一个 polyfill,然后才能运行节点脚本?
【问题讨论】:
标签: javascript node.js webpack