You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 14调用Web3智能合约时“无法解析url模块”错误的解决方法

Angular 14 Dapp调用Web3智能合约模块缺失问题解决方案

问题描述

在Angular 14去中心化应用中调用Web3智能合约函数this.manager = await report.methods.manager().call();时,出现模块找不到错误。已尝试npm i crypto、npm i http、安装url、添加webpack配置文件等方案,但问题仍未解决,应用无法加载。具体错误信息:

index.js:561 [webpack-dev-server] ERROR in ../../node_modules/web3-providers-ws/lib/helpers.js 11:12-26
Module not found: Error: Can't resolve 'url' in 'C:\Users\bpha\Angular\node_modules\web3-providers-ws\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "url": require.resolve("url/") }'
    - install 'url'
If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "url": false }

解决步骤

1. 安装必要依赖

执行以下命令安装url和Angular自定义webpack工具:

npm install url @angular-builders/custom-webpack --save-dev

同时安装Web3所需的其他Node核心模块polyfill:

npm install crypto-browserify stream-http https-browserify stream-browserify buffer --save-dev

2. 创建自定义Webpack配置文件

在项目根目录新建webpack.config.js,添加以下内容:

module.exports = {
  resolve: {
    fallback: {
      "url": require.resolve("url/"),
      "crypto": require.resolve("crypto-browserify"),
      "http": require.resolve("stream-http"),
      "https": require.resolve("https-browserify"),
      "stream": require.resolve("stream-browserify"),
      "buffer": require.resolve("buffer/")
    }
  },
  plugins: [
    new (require('webpack').ProvidePlugin)({
      Buffer: ['buffer', 'Buffer'],
    }),
  ]
};

3. 修改Angular CLI配置

打开angular.json,修改architect下的build和serve配置,替换builder并指定自定义webpack文件路径:

"architect": {
  "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./webpack.config.js"
      },
      // 保留原有其他配置(如outputPath、index、main等)
    }
  },
  "serve": {
    "builder": "@angular-builders/custom-webpack:dev-server",
    "options": {
      "customWebpackConfig": {
        "path": "./webpack.config.js"
      },
      // 保留原有其他配置(如browserTarget等)
    }
  }
}

4. 重启开发服务器

停止当前运行的ng serve,重新启动:

ng serve

说明

Angular CLI默认封装了Webpack配置,直接手动添加的webpack配置文件不会被识别。必须通过@angular-builders/custom-webpack插件来注入自定义配置,才能让Webpack正确加载所需的Node核心模块polyfill。

内容的提问来源于stack exchange,提问作者Baccarani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:27:31