🧊Webpack 5 Polyfill Issue

While setting up a new web3 project from scratch, you might face multiple issues with webpack 5. This issue is caused due to the fact that the web3.js and ethers.js packages have certain dependencies, which are 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 utilise the web3.js and ethers.js packages easily without any issues.

In this guide, we have added instructions of adding the polyfills of some of the commonly used web frameworks:

For React

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

Solution

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

  • Using

npm install --save-dev stream-browserify buffer crypto-browserify process os-browserify path-browserify constants-browserify
  • Create config-overrides.js in the root of your project folder with the content

const { ProvidePlugin }= require("webpack")

module.exports = {
  webpack: function (config, env) {
    config.module.rules = config.module.rules.map(rule => {
      if (rule.oneOf instanceof Array) {
        rule.oneOf[rule.oneOf.length - 1].exclude = [/\.(js|mjs|jsx|cjs|ts|tsx)$/, /\.html$/, /\.json$/];
      }
      return rule;
    });
    config.resolve.fallback = {
      ...config.resolve.fallback,
      stream: require.resolve("stream-browserify"),
      buffer: require.resolve("buffer"),
      crypto: require.resolve("crypto-browserify"),
      process: require.resolve("process"),
      os: require.resolve("os-browserify"),
      path: require.resolve("path-browserify"),
      constants: require.resolve("constants-browserify"), 
      fs: false
    }
    config.resolve.extensions = [...config.resolve.extensions, ".ts", ".js"]
    config.plugins = [
      ...config.plugins,
      new ProvidePlugin({
        Buffer: ["buffer", "Buffer"],
      }),
      new ProvidePlugin({
          process: ["process"]
      }),
    ]
    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-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts 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 function, add:

config.ignoreWarnings = [/Failed to parse source map/];

If you're using craco, similar changes need to be made to craco.config.js

If you have any questions, please feel free to ask on the Banana SDK Discord forum.

Last updated