BREAKING CHANGE: webpack<5 used to include polyfills for node.js

2024-05-09 16:53:20 浏览数 (3)

问题

在使用vue 3运行web3钱包项目时,突然出现以下报错信息:

代码语言:javascript复制
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: { "crypto": require.resolve("crypto-browserify") }'
    - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "crypto": false }
 @ ./node_modules/ethereumjs-wallet/dist.browser/index.js 175:19-42
 @ ./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/components/WalletsAPI.vue?vue&type=script&setup=true&lang=js 3:0-42 21:19-39 52:15-20
 @ ./src/components/WalletsAPI.vue?vue&type=script&setup=true&lang=js 1:0-213 1:0-213 1:214-416 1:214-416
 @ ./src/components/WalletsAPI.vue 2:0-72 3:0-67 3:0-67 6:49-55
 @ ./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/App.vue?vue&type=script&setup=true&lang=js 1:0-53 9:6-16
 @ ./src/App.vue?vue&type=script&setup=true&lang=js 1:0-200 1:0-200 1:201-390 1:201-390
 @ ./src/App.vue 2:0-65 3:0-60 3:0-60 6:49-55
 @ ./src/main.js 2:0-28 3:10-13

根据上面的提示,webpack5默认移除了node.js的核心模块,要使用的话需要手动引入。

解决办法

首先我们需要先按照下面的命令安装一个插件node-polyfill-webpack-plugin,用于在浏览器环境下模拟nodejs核心模块的功能:

代码语言:javascript复制
$ npm i node-polyfill-webpack-plugin

然后再安装crypto-browserify

代码语言:javascript复制
$ npm i crypto-browserify

最后在修完我们项目中的vue.config.js文件

代码语言:javascript复制
const { defineConfig } = require('@vue/cli-service')
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")  // add
module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack:{                                                // add
    plugins:[new NodePolyfillPlugin()]
  }
})

声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)[1]进行许可,使用时请注明出处。 Author: mengbin[2] blog: mengbin[3] Github: mengbin92[4] cnblogs: 恋水无意[5] 腾讯云开发者社区:孟斯特[6]

References

[1] 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0): https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh [2] mengbin: mengbin1992@outlook.com [3] mengbin: https://mengbin.top [4] mengbin92: https://mengbin92.github.io/ [5] 恋水无意: https://www.cnblogs.com/lianshuiwuyi/ [6] 孟斯特: https://cloud.tencent.com/developer/user/6649301

0 人点赞