Webpack 5 issue

Webpack 5 issue while including node libraries for web frameworks

From Webpack 5 in order to include the nodes-related libraries we need to follow a few steps. This is needed as the internal library we use in leap-near-sdk needed these polyfills.

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

  • React

  • Angular

  • Vue.js

React

create-react-app

If you are using create-react-app version >= 5 which internally has webpack version 5 as the internal dependency. We can't go ahead and re-configure the react-scripts. hence,

  • Install react-app-rewired

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

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:

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

Angular

If you are using Angular version >11,

Solution

  • Install the required dependencies within your angular project:

  • Within tsconfig.json add the following paths in compilerOptions so Webpack can get the correct dependencies

  • Add the following lines to polyfills.ts file:

Vue.js


If you are using vue.js you may run into issues building.

Solution

  • Install the missing modules

Add the following lines to vue.config.js

Vite/Svelte/Rollup

If you are using vite/svelte/rollup you may run into issues building.

Solution

  • Install the missing modules

Add the following lines to svelte.config.js or rollup.config.js or vite.config.js

Last updated