Taro 框架综述与上手指南
项目地址:https://github.com/NervJS/taro
文档:https://docs.taro.zone/
关联清单:https://github.com/justjavac/awesome-wechat-weapp
Taro 是一套“多端统一”开发框架,支持以 React/Vue/Nerv 等技术栈编写代码,编译到微信/支付宝/抖音等小程序和 H5/React Native 等多端。工程化能力与生态较为成熟,适合中大型团队与多端协同的业务场景。
🎯 目标
- 快速创建并运行一个 Taro 小程序项目
- 掌握页面路由、组件与网络请求的基础用法
- 理解工程化配置与常见问题
本文以 React 技术栈为例(Vue 用法参见官方文档)。
⚙️ 初始化与运行
安装 CLI 并创建项目:
bash
# 全局安装 CLI(根据本机权限自行选择)
npm i -g @tarojs/cli
# 创建项目(按向导选择 React + 小程序)
taro init my-taro-app
cd my-taro-app
开发与构建(以微信小程序为例):
bash
# 开发模式(监听编译)
npm run dev:weapp
# 生产构建
npm run build:weapp
构建后在项目根目录的 dist
生成小程序产物,用微信开发者工具“打开”该目录即可预览。
📁 核心目录结构(示例)
my-taro-app/
├─ src/
│ ├─ app.config.ts # 全局路由/窗口配置
│ ├─ app.tsx # 应用入口
│ ├─ pages/
│ │ └─ index/
│ │ ├─ index.config.ts
│ │ ├─ index.tsx
│ │ └─ index.scss
│ └─ services/ # 自定义请求封装
├─ package.json
└─ tsconfig.json
🚏 路由与页面
- 全局配置文件
src/app.config.ts
用于声明路由:
ts
export default defineAppConfig({
pages: [
'pages/index/index',
'pages/about/index'
],
window: {
navigationBarTitleText: 'Taro App',
navigationBarBackgroundColor: '#ffffff',
navigationBarTextStyle: 'black'
}
})
- 页面级配置
src/pages/index/index.config.ts
:
ts
export default definePageConfig({
navigationBarTitleText: '首页'
})
🧩 页面与组件(React)
页面示例:
tsx
// src/pages/index/index.tsx
import { View, Button, Text } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import './index.scss'
export default function Index() {
const [count, setCount] = useState(0)
useLoad(() => {
console.log('page onLoad')
})
return (
<View className='page'>
<Text>计数:{count}</Text>
<Button onClick={() => setCount(c => c + 1)}>+1</Button>
<Button onClick={() => Taro.navigateTo({ url: '/pages/about/index' })}>
跳转 About
</Button>
</View>
)
}
样式示例:
scss
/* src/pages/index/index.scss */
.page { padding: 24rpx; }
🌐 网络请求封装
Taro 提供跨端的请求 API:
ts
// src/services/http.ts
import Taro from '@tarojs/taro'
const BASE_URL = 'https://api.example.com'
export async function request<T>(url: string, options: Taro.request.Option = {}) {
const token = Taro.getStorageSync('token')
const res = await Taro.request<T>({
url: BASE_URL + url,
timeout: 10000,
header: { 'Content-Type': 'application/json', Authorization: token ? `Bearer \${token}` : '' },
...options
})
// 统一业务判断
const data: any = res.data
if (data && data.code === 0) return data.data as T
throw { code: data?.code ?? -1, message: data?.message ?? '业务错误', raw: data }
}
调用示例:
ts
// src/pages/index/index.tsx (片段)
import { request } from '@/services/http'
async function load() {
try {
const list = await request<any[]>('/items', { method: 'GET' })
console.log(list)
} catch (e) {
Taro.showToast({ title: '请求失败', icon: 'none' })
}
}
🏗️ 工程化实践
- 按需/分包:按页面拆分功能模块;使用 Taro 分包能力管理包体大小
- 状态管理:可选 Redux、MobX、Zustand 等(优先选团队熟悉方案)
- 资源治理:图片压缩、SVG 图标组件化、字体按需
- 观测与日志:埋点、错误上报与性能监控(如首屏耗时、请求错误率)
🧪 常见问题
- 第三方库依赖 DOM/浏览器 API:在小程序端不可用,选择跨端友好库或使用 polyfill/条件分支
- 构建后路径问题:以
dist
为根在微信开发者工具打开,确保基础库版本满足要求 - 单位与兼容:使用
rpx
适配;不同平台的组件/样式行为存在差异,需真机验证 - 小程序端能力差异:H5 可用的特性在小程序端可能受限,提前评估
✅ 适用场景
- 多端统一研发(小程序 + H5/APP)
- 中大型项目与多团队协作
- 工程化治理与可维护性要求高
🔗 参考
📊 总结
Taro 通过编译与跨端组件体系实现“一次开发,多端覆盖”。在小程序端落地时,重视真机验证、第三方依赖适配与分包策略,可获得稳定的交付体验。