uni-app 跨端小程序开发实践
项目地址:https://github.com/dcloudio/uni-app
文档:https://uniapp.dcloud.net.cn/
关联清单:https://github.com/justjavac/awesome-wechat-weapp
uni-app 基于 Vue 技术栈,支持编译到微信/支付宝/字节等多端小程序与 H5/APP。与 Vue 生态契合度高、上手快、模板与插件资源丰富,适合业务型项目快速落地。
🎯 目标
- 使用官方模板创建 uni-app 项目
- 掌握 pages.json 路由、页面与组件的基础用法
- 了解 uni.request 与条件编译
- 把控工程化与包体策略
⚙️ 初始化与运行
使用 Vite 预设模板(Vue3):
bash
# 使用 degit 拉取官方模板(或使用 HBuilderX 创建项目)
npx degit dcloudio/uni-preset-vue#vite my-uni-app
cd my-uni-app
npm i
运行到微信小程序:
bash
# 开发模式(微信小程序)
npm run dev:mp-weixin
# 生产构建
npm run build:mp-weixin
构建产物位于 dist/dev/mp-weixin
或 dist/build/mp-weixin
,用微信开发者工具“打开”该目录即可预览。
🗺️ 路由与页面(pages.json)
pages.json
用于声明页面与窗口配置:
json
{
"pages": [
{ "path": "pages/index/index", "style": { "navigationBarTitleText": "首页" } },
{ "path": "pages/about/index", "style": { "navigationBarTitleText": "关于" } }
],
"window": {
"navigationBarBackgroundColor": "#ffffff",
"navigationBarTextStyle": "black"
}
}
页面 SFC 示例(Vue3):
vue
<!-- pages/index/index.vue -->
<template>
<view class="page">
<text>计数:\{\{ count \}\}</text>
<button @click="count++">+1</button>
<button @click="goAbout">关于</button>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const count = ref(0)
function goAbout() {
uni.navigateTo({ url: '/pages/about/index' })
}
</script>
<style>
.page { padding: 24rpx; }
</style>
🌐 网络请求与封装
基础调用:
ts
uni.request({
url: 'https://api.example.com/items',
method: 'GET',
success: (res) => {
// 建议统一判断后端业务字段
console.log(res.data)
},
fail: () => {
uni.showToast({ title: '网络错误', icon: 'none' })
}
})
统一封装(示例):
ts
// src/services/http.ts
export function request<T>(url: string, options: UniApp.RequestOptions = {}) {
const token = uni.getStorageSync('token')
return new Promise<T>((resolve, reject) => {
uni.request({
url: 'https://api.example.com' + url,
timeout: 10000,
header: { 'Content-Type': 'application/json', Authorization: token ? `Bearer \${token}` : '' },
...options,
success: (res) => {
const data: any = res.data
if (data && data.code === 0) resolve(data.data as T)
else reject({ code: data?.code ?? -1, message: data?.message ?? '业务错误', raw: data })
},
fail: (err) => reject({ code: 0, message: '网络异常', raw: err })
})
})
}
🔀 条件编译与跨端差异
uni-app 支持条件编译指令,便于多端差异处理:
ts
// #ifdef MP-WEIXIN
console.log('仅在微信小程序端执行')
// #endif
// #ifdef H5
console.log('仅在 H5 端执行')
// #endif
常见跨端差异:
- 能力差异(如文件系统、Canvas):使用条件编译或封装适配层
- 组件差异:优先使用官方/生态里跨端兼容的组件
🏗️ 工程化与包体
- easycom 自动组件:遵循命名/目录约定可免注册;第三方组件建议放入
uni_modules
以便管理 - 分包:利用
pages.json
的subPackages
拆分业务,降低主包体积 - 资源治理:图片压缩、接口域名走配置、CDN 缓存
- 错误治理与埋点:统一封装 toast/dialog/log,上报关键错误
示例分包(片段):
json
{
"subPackages": [
{
"root": "pages-sub/user",
"pages": [{ "path": "profile/index", "style": { "navigationBarTitleText": "我的" } }]
}
]
}
🧪 常见问题
- 微信开发者工具 npm 构建:若引入第三方 npm 包,需在工具中开启“使用 npm 模块”并执行“构建 npm”
- 组件不生效:检查 easycom 命名与路径;或在页面
components
显式注册(旧方案) - pages.json 修改不生效:需重启编译/开发工具;确保路径正确且文件已保存
- 条件编译未按预期:确认注释语法与构建目标平台一致
✅ 适用场景
- 以 Vue 技术栈为主的前端团队
- 快速构建业务型小程序与 H5
- 多端覆盖但更偏向小程序与移动端
🔗 参考
- 文档:https://uniapp.dcloud.net.cn/
- 条件编译:https://uniapp.dcloud.net.cn/tutorial/platform.html
- 分包:https://uniapp.dcloud.net.cn/collocation/pages.html#subpackages
📊 总结
uni-app 在“上手速度”“生态整合”与“跨端覆盖”方面表现优秀。合理使用条件编译、分包与统一数据层,可在多端间保持一致的开发体验与交付质量。