模式切换
工程化
使用 npm 包
小程序支持使用 npm 包来扩展功能,特别是 UI 组件库能极大提高开发效率。
配置和使用 npm
步骤1:初始化 npm
bash
# 在项目根目录执行
npm init -y
步骤2:安装依赖
bash
# 安装 UI 组件库
npm install @vant/weapp
# 安装工具库
npm install lodash dayjs
步骤3:构建 npm 包
- 在微信开发者工具中点击:工具 → 构建 npm
- 或者使用命令行:
npm run build
(如果配置了脚本)
步骤4:在 app.json 中引入组件
json
{
"usingComponents": {
"van-button": "@vant/weapp/button/index",
"van-cell": "@vant/weapp/cell/index",
"van-cell-group": "@vant/weapp/cell-group/index"
}
}
使用 Vant Weapp UI 库
html
<!-- 使用 Vant 组件 -->
<van-cell-group>
<van-cell title="单元格" value="内容" />
<van-cell title="单元格" value="内容" label="描述信息" />
</van-cell-group>
<van-button type="primary">主要按钮</van-button>
<van-button type="info">信息按钮</van-button>
<van-field
label="用户名"
placeholder="请输入用户名"
value="{{ username }}"
bind:change="onUsernameChange"
/>
javascript
// 页面逻辑
Page({
data: {
username: ''
},
onUsernameChange: function(event) {
this.setData({
username: event.detail
})
}
})
使用工具库
javascript
// 使用 lodash 进行数据处理
const _ = require('lodash')
Page({
data: {
users: []
},
processUserData: function(rawData) {
// 使用 lodash 处理数据
const processedData = _.chain(rawData)
.filter(user => user.age > 18)
.sortBy('name')
.groupBy('department')
.value()
this.setData({ users: processedData })
},
debouncedSearch: _.debounce(function(keyword) {
this.searchAPI(keyword)
}, 300)
})
自定义 npm 脚本
json
// package.json
{
"name": "my-miniprogram",
"version": "1.0.0",
"scripts": {
"dev": "npm run build && npm run watch",
"build": "node ./scripts/build-npm.js",
"watch": "node ./scripts/watch.js",
"lint": "eslint . --ext .js",
"test": "jest"
},
"dependencies": {
"@vant/weapp": "^1.0.0",
"lodash": "^4.17.20",
"dayjs": "^1.10.4"
},
"devDependencies": {
"eslint": "^7.0.0",
"jest": "^26.0.0"
}
}
使用第三方框架进行跨端开发
Taro - React 语法风格
bash
# 安装 Taro CLI
npm install -g @tarojs/cli
# 创建项目
taro init my-app
# 开发小程序
cd my-app
npm run dev:weapp
jsx
// Taro 组件示例
import { Component } from 'react'
import { View, Text, Button } from '@tarojs/components'
import { request } from '@tarojs/taro'
class HomePage extends Component {
state = {
message: 'Hello Taro!'
}
handleClick = () => {
this.setState({ message: 'Button Clicked!' })
}
async fetchData() {
try {
const res = await request({
url: '/api/data'
})
this.setState({ data: res.data })
} catch (error) {
console.error('Request failed:', error)
}
}
render() {
return (
<View className="index">
<Text>{this.state.message}</Text>
<Button onClick={this.handleClick}>Click me</Button>
</View>
)
}
}
export default HomePage
Uni-app - Vue 语法风格
vue
<!-- Uni-app 页面示例 -->
<template>
<view class="container">
<text class="title">{{ title }}</text>
<button @click="handleClick">Click me</button>
<view v-for="item in list" :key="item.id">
{{ item.name }}
</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello Uni-app!',
list: []
}
},
methods: {
handleClick() {
uni.showToast({
title: 'Button Clicked!'
})
},
async fetchData() {
try {
const res = await uni.request({
url: '/api/data'
})
this.list = res.data
} catch (error) {
console.error('Request failed:', error)
}
}
},
onLoad() {
this.fetchData()
}
}
</script>
<style>
.container {
padding: 20rpx;
}
.title {
font-size: 36rpx;
color: #333;
}
</style>
框架选择考量
特性 | 原生开发 | Taro | Uni-app |
---|---|---|---|
学习成本 | 低 | 中(需懂 React) | 中(需懂 Vue) |
跨端能力 | 仅微信 | 微信、支付宝、H5 等 | 全端(微信、支付宝、H5、App 等) |
性能 | 最优 | 接近原生 | 接近原生 |
生态 | 微信官方 | 丰富 | 非常丰富 |
适用场景 | 单一平台、性能要求高 | 多端、React 技术栈 | 多端、Vue 技术栈 |
代码风格与规范
ESLint 配置
json
// .eslintrc.js
module.exports = {
env: {
es6: true,
browser: true,
node: true
},
extends: [
'eslint:recommended',
'@tencent/eslint-config-wechat'
],
rules: {
'indent': ['error', 2],
'quotes': ['error', 'single'],
'semi': ['error', 'never'],
'comma-dangle': ['error', 'never'],
'no-unused-vars': 'error',
'no-console': 'warn',
// 小程序特定规则
'wxapp/no-js-in-wxml': 'error',
'wxapp/no-this-in-wxs': 'error'
},
globals: {
wx: true,
App: true,
Page: true,
Component: true,
getApp: true,
getCurrentPages: true
}
}
目录结构规范
miniprogram/
├── components/ # 公共组件
│ ├── base/ # 基础组件
│ │ ├── button/
│ │ └── modal/
│ └── business/ # 业务组件
│ ├── product-card/
│ └── user-info/
├── pages/ # 页面
│ ├── index/
│ ├── user/
│ └── product/
├── services/ # 服务层
│ ├── api.js # API 接口
│ ├── request.js # 请求封装
│ └── cache.js # 缓存服务
├── utils/ # 工具函数
│ ├── index.js # 工具类入口
│ ├── validator.js # 验证器
│ └── formatter.js # 格式化工具
├── constants/ # 常量
│ ├── api.js # API 常量
│ └── config.js # 配置常量
├── assets/ # 静态资源
│ ├── images/
│ └── icons/
└── docs/ # 文档
├── README.md
└── CHANGELOG.md
JavaScript 规范
javascript
// ✅ 好的实践
// 使用 const/let
const BASE_URL = 'https://api.example.com'
let pageCount = 1
// 异步函数使用 async/await
class UserService {
async getUserInfo(userId) {
try {
const response = await this.request({
url: `${BASE_URL}/users/${userId}`,
method: 'GET'
})
return response.data
} catch (error) {
console.error('获取用户信息失败:', error)
throw error
}
}
// 使用解构赋值
updateUserProfile({ name, avatar, bio }) {
return this.request({
url: `${BASE_URL}/profile`,
method: 'POST',
data: { name, avatar, bio }
})
}
}
// 导出统一的工具类
const Formatter = {
formatPrice(price) {
return `¥${(price / 100).toFixed(2)}`
},
formatDate(timestamp) {
return new Date(timestamp).toLocaleDateString()
}
}
export default Formatter
CSS 命名规范(BEM)
css
/* 使用 BEM 命名规范 */
.product-card {} /* Block */
.product-card__image {} /* Element */
.product-card__image--large {} /* Modifier */
.product-card__title {}
.product-card__price {}
.user-profile {}
.user-profile__avatar {}
.user-profile__name {}
.user-profile__name--vip {}
/* 通用样式类 */
.text-center { text-align: center; }
.text-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.flex { display: flex; }
.flex-center {
display: flex;
align-items: center;
justify-content: center;
}
版本管理(Git)与团队协作
Git 工作流
bash
# 功能分支工作流
git checkout -b feature/user-authentication # 创建功能分支
git add .
git commit -m "feat: 实现用户登录功能
- 添加微信登录接口
- 实现用户信息获取
- 添加登录状态管理"
git push origin feature/user-authentication
# 创建 Pull Request 进行代码审查
Git 提交规范
bash
# 提交信息格式
<type>(<scope>): <subject>
# 示例
feat(auth): 添加微信登录功能
fix(payment): 修复支付回调问题
docs(readme): 更新项目文档
style(button): 调整按钮样式
refactor(api): 重构请求封装
test(user): 添加用户服务测试
.gitignore 配置
gitignore
# 依赖文件
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# 构建输出
dist/
build/
# 环境变量
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# IDE 文件
.vscode/
.idea/
*.swp
*.swo
# 系统文件
.DS_Store
Thumbs.db
# 小程序特定
project.private.config.json
代码审查清单
markdown
## 代码审查清单
### 功能实现
- [ ] 功能是否符合需求文档
- [ ] 边界情况是否处理
- [ ] 错误处理是否完善
### 代码质量
- [ ] 代码是否符合规范
- [ ] 是否有重复代码
- [ ] 函数是否职责单一
### 性能优化
- [ ] 是否合理使用 setData
- [ ] 图片是否优化
- [ ] 是否有内存泄漏风险
### 用户体验
- [ ] 加载状态是否友好
- [ ] 错误提示是否清晰
- [ ] 交互是否流畅
团队协作配置
json
// project.config.json - 个人配置(不提交到 Git)
{
"description": "项目个人配置文件",
"setting": {
"urlCheck": false,
"es6": true,
"enhance": true,
"postcss": true,
"minified": true
},
"libVersion": "2.14.1",
"appid": "your-personal-appid",
"projectname": "my-miniprogram"
}
json
// project.private.config.json - 团队共享配置
{
"description": "团队共享配置文件",
"projectname": "team-miniprogram",
"setting": {
"compileHotReLoad": true,
"skylineRenderEnable": false
}
}
自动化脚本
json
// package.json 中的自动化脚本
{
"scripts": {
"dev": "npm run build:npm && npm run watch",
"build:npm": "node scripts/build-npm.js",
"watch": "node scripts/watch.js",
"lint": "eslint . --ext .js --fix",
"lint:wxml": "wxml-lint ./**/*.wxml",
"test": "jest",
"test:coverage": "jest --coverage",
"build:prod": "npm run lint && npm run test && npm run build:npm",
"deploy": "npm run build:prod && cli upload --project-path ./ --version 1.0.0 --desc '生产环境部署'"
}
}
javascript
// scripts/build-npm.js - 自定义构建脚本
const { execSync } = require('child_process')
const fs = require('fs')
const path = require('path')
console.log('开始构建 npm...')
try {
// 执行微信开发者工具的 npm 构建
execSync('miniprogram-npm', { stdio: 'inherit' })
// 检查构建结果
const miniprogramNpmPath = path.join(__dirname, '../miniprogram_npm')
if (fs.existsSync(miniprogramNpmPath)) {
console.log('✅ npm 构建成功')
} else {
throw new Error('miniprogram_npm 目录未生成')
}
} catch (error) {
console.error('❌ npm 构建失败:', error)
process.exit(1)
}
通过实施这些工程化实践,你的小程序项目将具备:
- 可维护性:清晰的目录结构和代码规范
- 可扩展性:模块化设计和组件化开发
- 团队协作:统一的开发流程和代码审查
- 质量保障:自动化检查和测试
- 跨端能力:支持多平台开发