【发布时间】: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),但这会导致我出现上层错误。
- Npm 版本 - 8.5.0
- node.js 版本 - 17.5.0
- 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 依赖项可能导致优化救助。
【问题讨论】: