Solution·

Reown+Wagmi 在 UniApp+Vite 项目中的问题与解决方案

在 UniApp+Vite 框架中集成 Reown 和 Wagmi 时遇到的打包、兼容性、RPC 访问等常见问题及完整解决方案。

在 UniApp+Vite 项目中集成 Reown 和 Wagmi 实现 Web3 钱包连接时,会遇到一系列打包、兼容性和网络问题。本文总结了实际开发中遇到的问题及对应的解决方案。

问题 1:Wagmi 打包后出现异常文件名

现象

Wagmi 在本地开发环境运行一切正常,但执行 build 打包后,生成的文件中出现以 ..node 开头的文件,导致引入时报错。

解决方案

vite.config.tsbuild 配置中添加 rollupOptions,手动控制代码分包策略:

export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: (id) => {
          if (!id || typeof id !== 'string')
            return 'vendor'
          
          // 统一路径分隔符
          const normalizedId = id.replace(/\\/g, '/')
          if (!normalizedId.includes('node_modules'))
            return
          
          // 处理 @scope/package 和普通包
          const match = normalizedId.match(/node_modules\/(@[^/]+\/[^/]+|[^/]+)/)
          return match ? `vendor-${match[1].replace('@', '')}` : 'vendor'
        },
      },
    },
  },
})

此配置可以避免 Vite 生成异常的文件名,确保所有 node_modules 依赖都被正确打包到独立的 vendor chunk 中。

问题 2:插件要求 ES2020 编译目标

现象

Reown 和 Wagmi 插件在较低的编译目标下无法正常工作。

解决方案

vite.config.ts 中设置编译目标为 es2020

export default defineConfig({
  build: {
    target: 'es2020',
  },
})

问题 3:低版本手机无法连接钱包(一直转圈)

现象

在部分低版本 Android/iOS 设备上,Reown 连接钱包时一直显示加载状态,无法完成连接。

原因

低版本手机浏览器缺少现代 JavaScript API 的 polyfill 支持。

解决方案

安装 core-js 并在项目入口引入完整的 polyfill:

pnpm add core-js

main.tsapp.ts 入口文件顶部添加:

import 'core-js/stable'

这将为低版本浏览器提供完整的 ES6+ API polyfill 支持。

问题 4:写入合约后无法推送到区块链

现象

部分手机在执行写入合约操作时,虽然获取到了交易 hash,但交易始终无法推送到区块链网络,停留在 pending 状态。

原因

Gas 费用估算不准确或未正确设置导致交易无法被矿工打包。

解决方案

手动获取和设置 Gas 价格参数:

import { estimateFeesPerGas } from '@wagmi/core'

export async function getGasPrice() {
  const network = useAppKitNetwork()
  const fees = await estimateFeesPerGas(wagmiAdapter.wagmiConfig, {
    chainId: Number(network.value.chainId),
  })
  const maxFeePerGas = fees.maxFeePerGas
  const maxPriorityFeePerGas = fees.maxPriorityFeePerGas
  return { maxFeePerGas, maxPriorityFeePerGas }
}

在写入合约时传入这两个参数:

const { maxFeePerGas, maxPriorityFeePerGas } = await getGasPrice()

await writeContract({
  // ... 其他参数
  maxFeePerGas,
  maxPriorityFeePerGas,
})

问题 5:Reown 默认 RPC 国内无法访问

现象

Reown 默认使用的 RPC 节点在国内网络环境下无法访问,导致无法连接区块链网络。

解决方案

在初始化 wagmiAdaptercreateAppKit 时添加 customRpcUrls 参数,使用国内可访问的 RPC 节点:

const wagmiAdapter = new WagmiAdapter({
  // ... 其他配置
  customRpcUrls: {
    1: 'https://your-custom-rpc-url.com', // Ethereum Mainnet
    56: 'https://bsc-dataseed.binance.org', // BSC
    // 添加更多链的自定义 RPC
  },
})

createAppKit({
  adapters: [wagmiAdapter],
  // ... 其他配置
  customRpcUrls: {
    1: 'https://your-custom-rpc-url.com',
    56: 'https://bsc-dataseed.binance.org',
  },
})

问题 6:TypeScript 报错"实例化过深"

现象

在读写合约方法时,TypeScript 提示 "Type instantiation is excessively deep and possibly infinite"。

原因

完整的合约 ABI 文件过大,TypeScript 在进行类型推断时超出递归深度限制。

解决方案

不要存储完整的 ABI,只保留项目实际使用的方法:

// ❌ 不要这样做
import fullABI from './contract-full-abi.json'

// ✅ 应该这样做
const contractABI = [
  {
    name: 'transfer',
    type: 'function',
    inputs: [
      { name: 'to', type: 'address' },
      { name: 'amount', type: 'uint256' },
    ],
    outputs: [{ type: 'bool' }],
  },
  // 只包含项目需要使用的方法
] as const

问题 7:浮点数计算精度损失

现象

在处理 Token 金额、价格计算等涉及浮点数的场景时,JavaScript 原生运算会导致精度损失。

解决方案

使用专门的大数库处理计算和判断:

pnpm add big.js
# 或者
pnpm add bignumber.js
# 或者
pnpm add decimal.js

示例:

import Big from 'big.js'

// 使用 Big.js 进行精确计算
const amount1 = new Big('0.1')
const amount2 = new Big('0.2')
const result = amount1.plus(amount2) // 0.3(精确)

金额转换

使用 viem 提供的工具函数处理 Token 金额转换:

import { formatUnits, parseUnits } from 'viem'

// 将 wei 转换为可读单位
const displayAmount = formatUnits(1000000000000000000n, 18) // "1"

// 将可读单位转换为 wei
const weiAmount = parseUnits('1.5', 18) // 1500000000000000000n

总结

集成 Reown 和 Wagmi 到 UniApp+Vite 项目需要注意:

  1. 配置正确的 Vite 打包策略避免文件名异常
  2. 设置 ES2020 编译目标以支持现代特性
  3. 为低版本设备添加 polyfill 支持
  4. 手动设置 Gas 参数确保交易成功
  5. 使用自定义 RPC 节点解决网络访问问题
  6. 精简 ABI 避免 TypeScript 类型推断问题
  7. 使用专业库处理浮点数和大数运算

(注:文档内容由 Copilot 生成)

Built with qbimz • © 2026