【问题标题】:Angular 13 clean install wouldn't work with web3.jsAngular 13 全新安装不适用于 web3.js
【发布时间】:2022-07-20 04:17:58
【问题描述】:

我根本无法使用 web3 包,我在 polyfills.ts 文件中遇到错误,并且来自 Web3Js GitHub 的给定说明对我不起作用

复制这个的步骤: 使用 Angular cli 开始了一个新项目:

ng new test-app

然后根据他们的github说明继续安装web3及其依赖项

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

在此之后,我向 tsconfig.json 添加了一个附加属性(路径):

"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"],
}

最后将其添加到polyfills.ts 文件中

(window as any).global = window;
global.Buffer = Buffer;
global.process = {
    env: { DEBUG: undefined },
    version: '',
    nextTick: require('next-tick')
} as any;

不幸的是,这些更改不起作用,因为我在 polyfills.ts 中遇到了构建错误,更具体地说是以下错误:

找不到名称“全球”。

找不到名称“要求”。您需要为节点安装类型定义吗?尝试npm i --save-dev @types/node,然后将“节点”添加到 tsconfig 中的类型字段。

polyfills.ts 文件中的这些添加是必要的,否则我会收到此错误:

重大变化:webpack

如果你想包含一个 polyfill,你需要: - 添加一个后备 'resolve.fallback: { "url": require.resolve("url/") }' - 安装“网址” 如果您不想包含 polyfill,则可以使用这样的空模块: resolve.fallback: { "url": false }

在调试时我可以看到global 变量确实是未定义的。 我试图欺骗它在 func 级别声明它(如在其他一些 Stack Overflow 线程上发现的那样)(将 global 声明为 any,将 require 声明为 any),但这会导致我出现上层错误。

  1. Npm 版本 - 8.5.0
  2. node.js 版本 - 17.5.0
  3. web3 npm 包版本 - ^1.7.0

经过更多的试验和错误,我已经能够正确构建和提供所有上部更改,但是在我的代码中尝试使用 web3 时,我得到以下信息:

./node_modules/xhr2-cookies/dist/xml-http-request.js:43:10-24 - Error: Module not found: Error: Can't resolve 'url' in 'D:\Work\Tutorials\CryptoZombies\crypto-zombies-angular\node_modules\xhr2-cookies\dist'

重大变化:webpack

如果你想包含一个 polyfill,你需要: - 添加一个后备 'resolve.fallback: { "url": require.resolve("url/") }' - 安装“网址” 如果您不想包含 polyfill,则可以使用这样的空模块: resolve.fallback: { "url": false }

安装 url 和 xhr2-cookies 后,我能够运行它(即使我收到此警告:

CommonJS 或 AMD 依赖项可能导致优化救助。

【问题讨论】:

    标签: angular web3js


    【解决方案1】:

    所以今天我遇到了同样的问题,我在这个 github 存储库中找到了这个解决方案:https://github.com/ChainSafe/web3.js 在“Web3 和 Angular”下的自述文件中。

    这与您的解决方案基本相同,唯一的更改是您必须将其粘贴到您的 polyfills.ts 文件中:

    import { Buffer } from 'buffer';
    
    (window as any).global = window;
    global.Buffer = Buffer;
    global.process = {
        env: { DEBUG: undefined },
        version: '',
        nextTick: require('next-tick')
    } as any;
    

    这样我就不必安装任何额外的依赖项(在您的情况下为 xhr2-cookies)。

    【讨论】:

      【解决方案2】:

      我已经安装了 2 个古董包(url 和 xhr2-cookies)并让它工作,虽然它感觉不对,必须有一个更清洁的方法,因为我收到了关于正在使用的常见 js 依赖项的警告,并且可能正在制作我的包更大。

      【讨论】:

        猜你喜欢
        • 2015-07-11
        • 2019-06-06
        • 2022-06-14
        • 2022-01-08
        • 1970-01-01
        • 2022-07-14
        • 2020-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多