Bundler polyfill issues - React Native Metro
While setting up a new Web3 project from scratch, you might face bundler issues. This can occur because the
core packages like eccrypto have dependencies which are not present within the build environment.
To rectify this, the go-to method is to add the missing modules directly into the package, and edit the bundler configuration to use those. Although this approach works, it can significantly increase bundle size, leading to slower load times and a degraded user experience.
Some libraries rely on environment-specific modules that may be available at runtime in the browser even if they are not bundled. Libraries such as Embedded Wallets’ Web3Auth take advantage of this behavior and can function correctly without bundling all modules. However, if you are using a library that does not take advantage of this, you might face issues.
To avoid unnecessary overhead, include only the required polyfills, test functionality with care, and configure your bundler to ignore unresolved modules rather than including them in the final build.
We recommend that you require certain Node polyfills to be added to your project, while testing each of its functionalities. At the same time, instruct the bundler to ignore the missing modules, and not include them in the build.
In this guide, we provide instructions for adding polyfills in React Native Metro. The steps install the missing libraries required for module resolution and then configures Metro so they are not bundled unless needed at runtime.
Step 1: Install the missing modules
Check for the missing libraries in your build and included packages, and polyfill these. For Web3Auth, you
need to polyfill the buffer, process, crypto and stream libraries. For the rest of the libraries,
we are installing a dummy module called empty-module which helps us get rid of the warnings while building
the project.
- npm
- Yarn
- pnpm
- Bun
npm install --save empty-module readable-stream crypto-browserify react-native-get-random-values buffer process
yarn add empty-module readable-stream crypto-browserify react-native-get-random-values buffer process
pnpm add empty-module readable-stream crypto-browserify react-native-get-random-values buffer process
bun add empty-module readable-stream crypto-browserify react-native-get-random-values buffer process
If you're using any other blockchain library alongside Web3Auth, it's possible that you might need to polyfill more
libraries. Typically, the libraries like browserify-zlib, assert, stream-http, https-browserify,
os-browserify, url are commonly required.