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

Web3.eth.accounts.decrypt在Angular中报错cryp.createDecipheriv is not a function

Angular中Web3解密Version3 Keystore JSON失败:cryp.createDecipheriv is not a function问题解决

这个问题本质上是Angular的构建环境(Webpack)没有正确处理Node.js核心模块的浏览器兼容导致的,和Vue的差异在于两者默认的Webpack配置对Node模块的polyfill策略不同。下面是具体原因分析和解决步骤:

问题原因

Web3.js的accounts.decrypt方法依赖Node.js的crypto核心模块,但浏览器环境本身没有这个模块。Vue CLI的默认配置会自动为这类Node核心模块添加浏览器兼容的polyfill(比如crypto-browserify),而Angular的默认构建配置没有做这件事,导致运行时找不到createDecipheriv方法。

解决步骤

1. 安装浏览器端的crypto polyfill包

首先安装替代Node crypto的浏览器兼容包:

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

2. 修改Angular的Webpack配置

如果你的Angular项目是用Angular CLI创建的,需要自定义Webpack配置:

  • 先安装@angular-builders/custom-webpack:
    npm install @angular-builders/custom-webpack --save-dev
    
  • 在项目根目录创建webpack.config.js文件,添加模块别名配置:
    module.exports = {
      resolve: {
        fallback: {
          "crypto": require.resolve("crypto-browserify"),
          "stream": require.resolve("stream-browserify"),
          "assert": require.resolve("assert"),
          "http": require.resolve("stream-http"),
          "https": require.resolve("https-browserify"),
          "os": require.resolve("os-browserify"),
        }
      }
    };
    
  • 修改angular.json,将构建器替换为自定义Webpack:
    在projects -> [你的项目名] -> architect -> build下,修改配置:
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./webpack.config.js"
      },
      // 保留其他原有配置
    }
    
    同样在architect -> serve下也修改构建器:
    "builder": "@angular-builders/custom-webpack:dev-server"
    

3. 配置TypeScript支持

修改tsconfig.json,确保开启合成默认导入:

{
  "compilerOptions": {
    // 保留其他配置
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  }
}

4. 在polyfills.ts中导入必要模块

打开src/polyfills.ts,添加以下导入:

import 'crypto-browserify';
import 'stream-browserify';

可选:升级Web3.js版本

你当前使用的1.0.0-beta.34版本比较老旧,对浏览器环境的支持不完善。建议升级到最新稳定版(比如v1.x或v4.x),新版本对浏览器兼容的处理更好,可能不需要额外配置polyfill:

npm install web3@latest --save

验证修复

重新构建并运行Angular应用:

npm run build
ng serve

再执行解密代码,应该就能正常工作了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:16:41