web3.js
web3.js copied to clipboard
Angular 16+ and Web3js 4.0+ problem solving
Expected behavior
- Create a brand new Angular Application
-
npm install web3
- Try a simple test in
app.component
import { Component } from '@angular/core';
import { Web3 } from 'web3';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
Web3 = new Web3('http://127.0.0.1:8545');
}
- Able to use the library
Actual behavior
- The first error that is run into is
/node_modules/isomorphic-ws/index"' can only be default-imported using the 'allowSyntheticDefaultImports' flag
- So I added this to tsconfig as mentioned in many places online
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
- Still not working and getting errors like:
Uncaught ReferenceError: process is not defined
- I have tried almost every single thing I can find online but haven't had any luck.
Steps to reproduce the behavior
-
ng new my-first-project
(needs angular cli) - cd my-first-project
- Edit app.component as above
- ng serve
Logs
Included above.
Environment
@angular version ^16.1.0 (the latest version) web3 version ^4.0.3 npm version 9.8.1 node versoin 18.15.0
I've reproduced the error. I will investigate it deeper. thx for your contribution.
Thanks. I appreciate it! Let me know if there are any investigations I can help with on my end.
So the problem is util
package
here is some options how to solve it
- add webpack config to your angular
- in your case you can just add this code to main.ts
(window as any).process = {
env: { DEBUG: undefined },
};
here is related issues and threads: https://github.com/twilio/twilio-client.js/issues/284 https://github.com/browserify/node-util/issues/57#issuecomment-764436352
Thank you for your help on this @avkos we have tried both suggestions and ended up landing on doing option 2
in a polyfills.ts
added to the src
directory.
polyfills.ts
(window as any).process = {
env: { DEBUG: undefined },
};
angular.json
(partial file)
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/frontend",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": [
"zone.js",
"src/polyfills.ts"
],
This gets it all working well especially if the Web3 library is used in a deeper service inside Angular.
Follow up question. Should this remain the long term solution for Angular or is there a patch that could be worked on to assist with this?
this is a temp solution. we will fix this bug inside library
That's great news! Looking forward to it
I believe this issue is fixed as we removed polyfills from library, closing