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

Angular 17升级esbuild后第三方库无法解析crypto等Node内置模块

升级Angular 17 + esbuild时Node核心模块无法解析的问题

问题描述

升级加密应用到Angular 17并切换到esbuild构建工具后,出现Node核心模块(如crypto)无法解析的错误:

✘ [ERROR] Could not resolve "crypto"

    node_modules/@toruslabs/eccrypto/dist/eccrypto.esm.js:1:23:
      1 │ import nodeCrypto from 'crypto';
        ╵                        ~~~~~~~~

  The package "crypto" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.

已在tsconfig.json中配置路径映射,但该配置仅对src目录下的自研TypeScript文件生效,第三方依赖库仍报错,涉及的库及位置:

node_modules/dropbox/dist/Dropbox-sdk.min.js:706:204:
node_modules/eth-lib/lib/bytes.js:7:201:
node_modules/web3-eth-accounts/lib/index.js:27:82:

已尝试的配置

在tsconfig.json中添加了路径映射,但未解决第三方依赖的问题:

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

解决方案

由于Angular 17的esbuild构建器不会读取tsconfig.json中的paths来解析第三方依赖,需要直接在angular.json中配置esbuild的模块解析别名:

  1. 确保已安装所有需要的浏览器兼容包:
npm install crypto-browserify stream-browserify os-browserify https-browserify stream-http url --save-dev
  1. 修改angular.json中项目的构建配置,在build.options下添加resolve.alias配置:
"architect": {
  "build": {
    "builder": "@angular-devkit/build-angular:application",
    "options": {
      // 其他原有配置...
      "resolve": {
        "alias": {
          "crypto": "crypto-browserify",
          "stream": "stream-browserify",
          "os": "os-browserify",
          "https": "https-browserify",
          "http": "stream-http",
          "url": "url"
        }
      }
    }
  }
}
  1. 若使用开发服务器,同样在serve.options下添加相同的resolve.alias配置,确保开发环境也能正常解析:
"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    // 其他原有配置...
    "resolve": {
      "alias": {
        "crypto": "crypto-browserify",
        "stream": "stream-browserify",
        "os": "os-browserify",
        "https": "https-browserify",
        "http": "stream-http",
        "url": "url"
      }
    }
  }
}

原理说明

tsconfig.json的paths仅用于TypeScript编译器对项目内源码的模块解析,而esbuild作为构建工具,其模块解析逻辑独立于TypeScript,因此需要直接在esbuild的配置中设置别名,让它将Node核心模块替换为对应的浏览器兼容实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 03:00:58