根本原因 webpack5 不支持 web3
- 报错信息:
ERROR in ../node_modules/web3-providers-ws/lib/helpers.js 11:12-26
Module not found: Error: Can't resolve 'url' in 'E:\code\project2022\project220707\2022071601\node_modules\web3-providers-ws\lib'
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: { "url": require.resolve("url/") }'
- install 'url'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "url": false }
解决方案:
Troubleshooting and known issues.
Web3 and Create-react-app
If you are using create-react-app version >=5 you may run into issues building. This is because NodeJS polyfills are not included in the latest version of create-react-app.
yarn add --dev react-app-rewired process crypto-browserify stream-browserify assert stream-http https-browserify os-browserify url buffer
- Create config-overrides.js in the root of your project folder with the content:
const webpack = require('webpack');
module.exports = function override(config) {
const fallback = config.resolve.fallback || {};
Object.assign(fallback, {
"crypto": require.resolve("crypto-browserify"),
"stream": require.resolve("stream-browserify"),
"assert": require.resolve("assert"),
"http": require.resolve("stream-http"),
"https": require.resolve("https-browserify"),
"os": require.resolve("os-browserify"),
"url": require.resolve("url")
})
config.resolve.fallback = fallback;
config.plugins = (config.plugins || []).concat([
new webpack.ProvidePlugin({
process: 'process/browser',
Buffer: ['buffer', 'Buffer']
})
])
return config;
}
- Within package.json change the scripts field for start, build and test. Instead of react-scripts replace it with react-app-rewired
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},
The missing Nodejs polyfills should be included now and your app should be functional with web3.
- If you want to hide the warnings created by the console:
In config-overrides.js within the override function, add:
config.ignoreWarnings = [/Failed to parse source map/];