Web3 working with Webpack 5 in Create React App

If you found this post, you are like me and like to build blockchain dApps. Until recently all was good in our decentralized utopia, until Webpack decided not to include Node polyfills.

i.e

Soooo… if this image has plagued you for hours, days or maybe weeks? Behold the following is a solution for Create React App without having make a vanilla React environment with manual Webpack and babel configs or ejecting the CRA.

Enter react-app-rewired, install it.

npm i react-app-rewired 

Now we need to actually install the missing packages.

npm i stream-browserify
npm i stream-http
npm i https-browserify
npm i os-browserify
npm i assert
npm i url

or if you like to be efficient.

npm i stream-browserify stream-http https-browserify os-browserify assert url

*these are the missing packages I needed, your needs might differ slightly, if so look through the error message, find the package on NPM, install it and add it to the overrides. You got this!


🧙🏼‍♂️Magical Overrides

Now in the root of your project, create a file called config-overrides.js.

Fill it with the following incantations…

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']
        })
    ])
    config.ignoreWarnings = [/Failed to parse source map/];
    return config;
}

Package.json

Now find and replace…

	"scripts": {
		"start": "react-scripts start",
		"build": "react-scripts build",
		"test": "react-scripts test",
		"eject": "react-scripts eject"
	},

with..

  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },

save, restart and enjoy life again! BOOMSHAKALAKA!!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *