Angular + web3.js: Module not found: Error: Can't resolve 'crypto'

Angular + web3.js: Module not found: Error: Can't resolve 'crypto'

我正在尝试开始使用 Angular 和 Web3.js 来处理一些以太坊合约。重现:

  1. ng 新
  2. npm install web3 --save
  3. ng 服务

package.json:

{
  "name": "ng-eth",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~11.0.6",
    "@angular/common": "~11.0.6",
    "@angular/compiler": "~11.0.6",
    "@angular/core": "~11.0.6",
    "@angular/forms": "~11.0.6",
    "@angular/platform-browser": "~11.0.6",
    "@angular/platform-browser-dynamic": "~11.0.6",
    "@angular/router": "~11.0.6",
    "rxjs": "~6.6.0",
    "tslib": "^2.0.0",
    "web3": "^1.3.4",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.1100.6",
    "@angular/cli": "~11.0.6",
    "@angular/compiler-cli": "~11.0.6",
    "@types/jasmine": "~3.6.0",
    "@types/node": "^12.11.1",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~5.1.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~4.0.2"
  }
}

app.component.ts:

import { Component, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import Web3 from "web3";


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'ngEth';
  
  private window: any;
  
  constructor(@Inject(DOCUMENT) private document: Document)
  {
    this.window = this.document.defaultView;
  }
  
  ngOnInit() {
    
       if (this.window.ethereum) {
        this.window.web3 = new Web3(this.window.ethereum);
        this.window.ethereum.enable();
        return true;
      }
  }
  
}

错误:./node_modules/eth-lib/lib/bytes.js 找不到模块:错误:无法解析 'C:\Users\profile\Documents\projects\ATS\ngEth\ngEth\node_modules\eth-lib\lib'

中的 'crypto'

错误:./node_modules/web3-eth-accounts/lib/index.js 找不到模块:错误:无法解析 'C:\Users\profile\Documents\projects\ATS\ngEth\ngEth\node_modules\web3-eth-accounts\lib'

中的 'crypto'

错误:./node_modules/web3-eth-accounts/node_modules/eth-lib/lib/bytes.js 找不到模块:错误:无法解析 'C:\Users\profile\Documents\projects\ATS\ngEth\ngEth\node_modules\web3-eth-accounts\node_modules\eth-lib\lib'

中的 'crypto'

错误:./node_modules/web3-providers-http/lib/index.js 找不到模块:错误:无法解析 'C:\Users\profile\Documents\projects\ATS\ngEth\ngEth\node_modules\web3-providers-http\lib'

中的 'http'

错误:./node_modules/xhr2-cookies/dist/xml-http-request.js 找不到模块:错误:无法解析 'C:\Users\profile\Documents\projects\ATS\ngEth\ngEth\node_modules\xhr2-cookies\dist'

中的 'http'

错误:./node_modules/web3-providers-http/lib/index.js 找不到模块:错误:无法解析 'C:\Users\profile\Documents\projects\ATS\ngEth\ngEth\node_modules\web3-providers-http\lib'

中的 'https'

错误:./node_modules/xhr2-cookies/dist/xml-http-request.js 找不到模块:错误:无法解析 'C:\Users\profile\Documents\projects\ATS\ngEth\ngEth\node_modules\xhr2-cookies\dist'

中的 'https'

错误:./node_modules/xhr2-cookies/dist/xml-http-request.js 找不到模块:错误:无法解析 'C:\Users\profile\Documents\projects\ATS\ngEth\ngEth\node_modules\xhr2-cookies\dist'

中的 'os'

错误:./node_modules/cipher-base/index.js 找不到模块:错误:无法在 'C:\Users\profile\Documents\projects\ATS\ngEth\ngEth\node_modules\cipher-base'

中解析 'stream'

错误:./node_modules/keccak/lib/api/keccak.js 找不到模块:错误:无法解析 'C:\Users\profile\Documents\projects\ATS\ngEth\ngEth\node_modules\keccak\lib\api'

中的 'stream'

错误:./node_modules/keccak/lib/api/shake.js 找不到模块:错误:无法解析 'C:\Users\profile\Documents\projects\ATS\ngEth\ngEth\node_modules\keccak\lib\api'

中的 'stream'

使其工作的最简单方法是修补由 Angular CLI 生成的 webpack.config.js

方法一(无需额外依赖)

在您的应用程序的根文件夹中创建 web3-patch.js 文件。

const fs = require('fs');

// path can differ depend on Angular CLI version
const browserConfigPath = 'node_modules/@angular-devkit/build-angular/src/webpack/configs/browser.js';

fs.readFile(browserConfigPath, 'utf8', function (err, data) {
  if (err) {
    return console.log(err);
  }
  const result = data.replace(/node: false/g, 'node: {crypto: true, stream: true}');

  fs.writeFile(browserConfigPath, result, 'utf8', function (err) {
    if (err) return console.log(err);
  });
});

在安装后执行此脚本

package.json

"scripts": {
  "start": "ng serve",
  ...
  "postinstall": "node web3-patch.js"
},

方法二

使用允许您扩展 Angular CLI 的模块:ngx-build-plus or @angular-builders/custom-webpack

执行原理图

ng add ngx-build-plus

创建webpack.config.js

module.exports = {
  node: { crypto: true, stream: true }
};

更新angular.json

"architect": {
  "build": {
    "builder": "ngx-build-plus:browser",
    "options": {
      ...
      "styles": [
        "src/styles.css"
      ],
      "scripts": [],
      "extraWebpackConfig": "webpack.config.js" <== add this
    },
    "configurations": {
      ...
  },
  "serve": {
    "builder": "ngx-build-plus:dev-server",
    "options": {
      "browserTarget": "cli1125:build",
      "extraWebpackConfig": "webpack.config.js" <== add this
    },
    ...
  },

在Angular12中,由于webpack 5升级,@yurzui发布的解决方案不再有效。

要修复编译错误,您需要安装所需的依赖项:

npm install crypto-browserify stream-browserify assert stream-http https-browserify os-browserify

然后你可以使用tsconfig路径指向所需的库:

tsconfig.json

{
  "compilerOptions": {
    "paths" : {
      "crypto": ["./node_modules/crypto-browserify"],
      "stream": ["./node_modules/stream-browserify"],
      "assert": ["./node_modules/assert"],
      "http": ["./node_modules/stream-http"],
      "https": ["./node_modules/https-browserify"],
      "os": ["./node_modules/os-browserify"],
    }
  }
}

来源:https://github.com/ChainSafe/web3.js/issues/4070