reactjs - 在 React.js 项目中使用 Vite 和 TypeScript 搭配 Web3.js 时出现错误:“模块 'events' 已为浏览器兼容性而外部化”
我正在开发一个使用 TypeScript 和 Vite 管理的 React.js 项目,并且在尝试集成 Web3.js 以与以太坊智能合约通信时遇到了问题。该项目设置为连接到运行在 Ganache 上的本地区块链,地址为 http://localhost:7545。
我使用 npm install web3 安装了 Web3.js,并尝试像这样创建一个 Web3 实例:
import Web3 from 'web3';
const web3 = new Web3(Web3.givenProvider || 'http://localhost:7545');
然而,一旦我调用任何 Web3.js 函数,例如 const web3=new Web3(Web3.givenProvider || 'http://localhost:7545'); 或 Web3.version,我就在控制台收到以下警告和错误:
Module "events" has been externalized for browser compatibility. Cannot access "events.EventEmitter" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.Uncaught TypeError: Class extends value undefined is not a constructor or null at common.ts:58:29 (anonymous) @ common.ts:58
这是一个用 Vite 管理的 React.js 项目,我对现代前端技术栈的经验有限。我想知道是否需要执行额外的配置或设置,才能将 Web3.js 成功集成到我的前端项目中。
任何关于如何解决这些问题以及在我的 React.js/Vite/TypeScript 项目中正确配置 Web3.js 的指导、建议或见解都将不胜感激。
答案#1
由于浏览器不支持 Node 的核心模块,使用它们的包必须进行填充(polyfill)才能在浏览器环境中运行。为了防止运行时错误,当你的代码引用像 fs 或 path 这样的内置模块时,Vite 会产生错误或警告。
你缺少 Node 的 polyfill。你可以通过安装 vite-plugin-node-polyfills 并在你的 vite.config 中添加 events polyfill 来解决。只需按照 npm 页面上的 README 操作,你就可以了。
答案#2
为了完整起见,以下是为社区解决我问题的步骤:
- 在项目目录中运行
npm install --save-dev vite-plugin-node-polyfills以安装vite-plugin-node-polyfills。 - 将
nodePolyfills插件添加到你的vite.config.ts文件中:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import {nodePolyfills} from 'vite-plugin-node-polyfills';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), nodePolyfills()],
})
