vite 使用 web3, walletConnect 报错

因为 web3 在 其他 环境中(比如 webpack, @vue/cli)运行,它们本身会下载一些依赖包,而 vite将不需要的包删除了,所以它没有 Buffer global 或者 process.env

如果要在vite 环境中运行,引入的包改为

import Web3 from 'web3/dist/web3.min.js'

参考链接:GitHub - ChainSafe/web3.js: Ethereum JavaScript API

可以配置 vite.config.js 将 web3 alias 设置为 'web3/dist/web3.min.js',这样便可以直接引入 web3

=====================

web3 这个库和 ethersjs 这个库的方向都是一样的

相对于 web3 ,ethers 实现更加适合初学者,而且拆的也比较细

所以建议大家使用 ethersjs 这个库

ethers.js

What is ethers.js — ethers.js 3.0.0 documentation

web3.js

Introduction — Web3.py 5.29.2 documentation

 ================================

使用 walletConnector 的时候会报错 global is not define

参考官方网站,是因为 walletConnetor 还是很依赖很多 nodejs 的运行环境的包的

这个解决方法也可以解决 web3 全局没有的报错

下载 @esbuild-plugins/node-globals-polyfill 这个包

yarn add -D @esbuild-plugins/node-globals-polyfill

yarn add -D stream-browserify

yarn add -D crypto-browserify
// 或者用 npm 下载

npm install -D @esbuild-plugins/node-globals-polyfill

npm install -D stream-browserify

npm install -D crypto-browserify

 然后在 vite.config.js 中配置一下

import { defineConfig } from 'vite'

import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'

//if you're using a create-vite framework template, you can also 
//import the vite plugin for that specific framework and add it in vite.config.js
//for more support. 
//For example, for vite.js react-ts template, you need to:
//import react from '@vitejs/plugin-react'
// and then add plugins: [react()] below

export default defineConfig({
  resolve: {
    alias: {
      stream: "stream-browserify",
      crypto: 'crypto-browserify',
      assert: 'assert'
    },
  },
  optimizeDeps: {
    esbuildOptions: {
      // Node.js global to browser globalThis
      define: {
        global: "globalThis",
      },
      // Enable esbuild polyfill plugins
      plugins: [
        NodeGlobalsPolyfillPlugin({
          process: true,
          buffer: true,
        }),
      ],
    },
  },
});

参考

Core - Blocknative Documentation

个人觉得这种配置还是太麻烦了,那么我们就需要知道为什么它需要 nodejs 的包,以后遇到这种问题怎么办?每次都看看我的文章吗?

我们仔细想一下,为什么 web 前端项目会需要 nodejs 的包啊,这不是搞笑呢么。

因为我们平时开发的环境都是运行时的环境,可以理解为运行的过程中会进行各种乱七八糟编译的环境

但是其实我们的 web 环境要的东西很简单,就是最终的那个 .js 文件,因为我们只能运行 .js 文件

所以我们只需要查看他们的库里的最终的 js 模块,可以直接去 node_modules/xxx 里去找,找到那个 .min.js 就是它最终打包的编译好的文件(一般都会有,没有再说)

猜你喜欢

转载自blog.csdn.net/weixin_42335036/article/details/124666053