In this tutorial, you’ll learn how to polyfill node core modules in webpack version 5 and above using the react-app-rewired package, installing the required dependencies, and overriding the default webpack configuration.
What causes the Polyfill node core module error?
Until the latest update to webpack version ___, webpack < 5 used to include NodeJS polyfills by default. Because the current version of webpack no longer includes NodeJS polyfills by default, it is causing issues for developers that use create-react-app with webpack > 5 to build applications with the web3.js and alchemyweb3.js library.
Here’s what the polyfill node core module error looks like:
4 easy steps to fix polyfill node core modules in webpack 5
The main issue with create-react-app and the polyfill error is that create-react-app, by default, hides the webpack config file inside the node-modules, and by doing so, generates the file at build time leaving developers unable to modify it.
Luckily there is a package, react-app-rewired, that allows developers to easily edit the webpack config file and fix the polyfill node core module error.
1. Install react-app-rewired
First, install the reach-app-rewired package with your preferred package manager.
Install react-app-rewired package with yarn:
Install react-app-rewired package with npm:
2. Install missing dependencies
Next, install these missing dependencies:
Install missing dependencies with yarn:
Install missing dependencies with npm:
3. Override the create-react-app webpack config file
In the root folder of your project, create a new file called config-overrides.js, and add the following code to it:
This config-overrides.js code snippet is telling webpack how to resolve the missing dependencies that are needed to support web3 libraries and wallet providers in the browser.
4. Override package.json to include the webpack configuration
Within the package.json file, replace react-scripts with react-app-rewired scripts for the three following scripts fields to update the webpack configuration:
Here’s what the package.json file looks like before replacing the react-scripts:
Here’s the package.json file after replacing the react-scripts with react-app-rewired scripts:
Now, the polyfill node core module error should be fixed, missing NodeJS polyfills should be included in your app, and your app should work with the web3.js and Alchemyweb3.js library.