I am having problems with importing web3 into reactjs. To replicate my problem, initiallize a new react app as so
npx create-react-app my-app
cd my-app
then open terminal in this location. Write:
npm install web3
npm install
in the App,js file add the following line
import Web3 from "web3";
I got the error after I do npm start
then I got the unsolved error which is
Module not found: Error: Can't resolve 'stream'
Module not found: Error: Can't resolve 'crypto'
I tried finding a solution online, in particular I tried each of
None seem to work with me. Is there any advice on how to solve this problem? Thank you!
This is my solution as of Feb 2, 2022. This might change at a future date.
After initiating a React app as so
npx create-react-app my-app
cd my-app
you will need to install a few packages:
npm i web3, react-app-rewired, url, assert, buffer, crypto-browserify, stream-http, https-browserify, stream-browserify, os-browserify
Then you open your favourite code editor in my case it is MS VS Code editor as so on your terminal
code .
Create a JS file in the Root directory as config-overrides.js
Copy and paste the code available here
const webpack = require('webpack');
module.exports = function override(config, env) {
//do stuff with the webpack config...
config.resolve.fallback = {
url: require.resolve('url'),
assert: require.resolve('assert'),
crypto: require.resolve('crypto-browserify'),
http: require.resolve('stream-http'),
https: require.resolve('https-browserify'),
os: require.resolve('os-browserify/browser'),
buffer: require.resolve('buffer'),
stream: require.resolve('stream-browserify'),
};
config.plugins.push(
new webpack.ProvidePlugin({
process: 'process/browser',
Buffer: ['buffer', 'Buffer'],
}),
);
return config;
}
Open the package.json
changed the scripts
commands to this:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
This has solved the problem for me!