跳转到主要内容

React - 用于构建用户界面的库

React 目前是最流行的 UI 框架之一。我们将帮助你配置 React + Vite 构建器与 @injectivelabs 包以及一些 polyfill,因为你需要它们来与加密钱包交互。

1. 安装 React

按照 Vite 文档中的入门指南设置你的应用。
$ npm create vite@latest

2. 安装 @injectivelabs 包

你可以使用 yarn 安装 @injectivelabs 包。
$ yarn add @injectivelabs/sdk-ts @injectivelabs/networks @injectivelabs/ts-types @injectivelabs/utils

## 如果你需要钱包连接
$ yarn add @injectivelabs/wallet-strategy
这些是 injective-ts monorepo 中最常用的包。

3. 配置 Vite 并添加 polyfill

首先,添加所需的 polyfill 包和 buffer
任何加密相关去中心化应用的主要依赖之一是 Buffer。为了确保我们将 Buffer 添加到项目中,我们可以将其作为依赖项安装,然后将其导入到 global/window 对象。下面分享了示例 vite.config.ts
$ yarn add @bangjelkoski/node-stdlib-browser
$ yarn add -D @bangjelkoski/vite-plugin-node-polyfills
$ yarn add buffer
最后,确保在 main.tsx 文件顶部导入 buffer
import { Buffer } from "buffer";

if (!window.Buffer) {
    window.Buffer = Buffer; // 可选,用于期望 Buffer 为全局变量的包
}

4. 使用状态管理

React 有很多不同的状态管理器,选择你要使用的并安装它。你可以使用内置的 Context API 进行状态管理,而无需安装第三方解决方案。首选的第三方状态管理器是 ReduxZustand
$ yarn add zustand

5. vite.config.ts

最后一步是配置 Vite 使用我们之前安装的 node-polyfills 打开 vite.config.ts 并在 plugins 数组中添加 node-polyfills 你的配置应该如下所示:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import { nodePolyfills } from "@bangjelkoski/vite-plugin-node-polyfills";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), nodePolyfills({ protocolImports: true })],
  define: {
    global: "globalThis",
  },
  resolve: {
    alias: {
      // 其他
      buffer: "buffer/",
    },
  },
  optimizeDeps: {
    include: ["buffer"],
  },
});

8. 启动我们的应用

最后,你可以使用 yarn dev 在本地启动应用,或使用 yarn build 构建生产版本,然后可以部署到任何静态页面托管服务,如 Netlify、Vercel 等。