Webpack 5 Polyfills Issue in React

While setting up a new web3 project from scratch, facing multiple issues with webpack 5?

This issue is caused because the web3.js and ethers.js packages have certain dependencies not present within the browser environment by webpack 5. Hence, you require certain node polyfills to be added to your project while overriding the configurations to enable their usage. When that is done, your project should be able to utilize the web3.js and ethers.js packages efficiently without any issues.

If you are using the create-react-app version >= 5, you may run into issues building. The problem can be resolved following the instructions below:

  • Install react-app-rewired and the missing modules into your application

    npm install --save-dev react-app-rewired crypto-browserify stream-browserify assert stream-http https-browserify os-browserify url buffer process
    
  • 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"],
        }),
      ]);
      config.ignoreWarnings = [/Failed to parse source map/];
      config.module.rules.push({
        test: /\.(js|mjs|jsx)$/,
        enforce: "pre",
        loader: require.resolve("source-map-loader"),
        resolve: {
          fullySpecified: false,
        },
      });
      return config;
    };
    
  • Within package.json, change the scripts field for start, build, and test. Instead of react-scripts, replace it with react-app-rewired.

    Before

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

    After

    "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.

Read more about this on our documentation page.