UniApp 微信小程序流水线发布全流程

1. 准备工作

开发环境配置

bash 复制代码
bash
# 安装 HBuilderX 或使用 CLI
npm install -g @vue/cli
npm install -g @dcloudio/uni-cli

# 创建项目
vue create -p dcloudio/uni-preset-vue#vue3 my-project

微信开发者工具配置

  1. 下载安装微信开发者工具
  2. 在设置中开启"安全端口"
  3. 获取 AppID(在微信公众平台获取)

2. 项目配置

manifest.json 配置

json 复制代码
json
{
    "name": "小程序名称",
    "appid": "your-app-id",
    "description": "",
    "versionName": "1.0.0",
    "versionCode": "100",
    "transformPx": false,
    "app-plus": {
        "usingComponents": true
    },
    "mp-weixin": {
        "appid": "your-app-id",
        "setting": {
            "urlCheck": false,
            "es6": true,
            "enhance": true,
            "postcss": true,
            "preloadBackgroundData": false,
            "minified": true,
            "newFeature": false,
            "coverView": true,
            "nodeModules": false,
            "autoAudits": false,
            "showShadowRootInWxmlPanel": true,
            "scopeDataCheck": false,
            "uglifyFileName": false,
            "checkInvalidKey": true,
            "checkSiteMap": true,
            "uploadWithSourceMap": true,
            "compileHotReLoad": false,
            "useMultiFrameRuntime": true,
            "useApiHook": true,
            "babelSetting": {
                "ignore": [],
                "disablePlugins": [],
                "outputPath": ""
            },
            "enableEngineNative": false,
            "bundle": false,
            "useIsolateContext": true,
            "useCompilerModule": true,
            "userConfirmedUseCompilerModuleSwitch": false,
            "userConfirmedBundleSwitch": false,
            "packNpmManually": false,
            "packNpmRelationList": [],
            "minifyWXSS": true
        },
        "usingComponents": true,
        "permission": {
            "scope.userLocation": {
                "desc": "你的位置信息将用于小程序位置接口的效果展示"
            }
        }
    }
}

pages.json 页面配置

json 复制代码
json
{
    "pages": [
        {
            "path": "pages/index/index",
            "style": {
                "navigationBarTitleText": "首页"
            }
        }
    ],
    "globalStyle": {
        "navigationBarTextStyle": "black",
        "navigationBarTitleText": "uni-app",
        "navigationBarBackgroundColor": "#F8F8F8",
        "backgroundColor": "#F8F8F8"
    },
    "condition": {
        "current": 0,
        "list": [
            {
                "name": "首页",
                "path": "pages/index/index"
            }
        ]
    }
}

3. CI/CD 流水线配置

GitHub Actions 示例

yaml 复制代码
yaml
# .github/workflows/deploy.yml
name: Deploy to WeChat Mini Program

on:
  push:
    branches:
      - main
  release:
    types: [published]

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v3
      
    - name: Setup Node.js
      uses: actions/setup-node@v3
      with:
        node-version: '16'
        
    - name: Install dependencies
      run: npm install
      
    - name: Build for MP-Weixin
      run: npm run build:mp-wechat
      
    - name: Upload to WeChat DevTools
      uses: actions/upload-artifact@v3
      with:
        name: mp-wechat-dist
        path: dist/dev/mp-weixin/
        
    - name: Deploy to WeChat Mini Program
      if: github.event_name == 'release'
      env:
        WECHAT_APP_ID: ${{ secrets.WECHAT_APP_ID }}
        WECHAT_PRIVATE_KEY: ${{ secrets.WECHAT_PRIVATE_KEY }}
      run: |
        # 使用微信官方CLI工具上传代码
        npx miniprogram-ci upload \
          --project-path ./dist/build/mp-weixin \
          --appid $WECHAT_APP_ID \
          --private-key "$WECHAT_PRIVATE_KEY" \
          --desc "CI自动部署 ${{ github.sha }}"

GitLab CI 示例

yaml 复制代码
yaml
# .gitlab-ci.yml
stages:
  - build
  - deploy

variables:
  NODE_VERSION: "16"

before_script:
  - node --version
  - npm --version

build_mp:
  stage: build
  image: node:$NODE_VERSION
  script:
    - npm install
    - npm run build:mp-weixin
  artifacts:
    paths:
      - dist/build/mp-weixin/
    expire_in: 1 week
  only:
    - main

deploy_mp:
  stage: deploy
  image: node:$NODE_VERSION
  script:
    - npm install miniprogram-ci
    - npx miniprogram-ci upload \
        --project-path ./dist/build/mp-weixin \
        --appid $WECHAT_APP_ID \
        --private-key "$WECHAT_PRIVATE_KEY" \
        --desc "GitLab CI部署 $CI_COMMIT_SHA"
  environment:
    name: production
  only:
    - tags
  dependencies:
    - build_mp

4. 微信小程序 CI 工具配置

安装微信小程序 CI

css 复制代码
bash
npm install miniprogram-ci --save-dev

创建上传脚本

php 复制代码
javascript
// scripts/upload.js
const ci = require('miniprogram-ci')
const path = require('path')

const project = new ci.Project({
  appid: process.env.WECHAT_APP_ID,
  type: 'miniProgram',
  projectPath: path.resolve('./dist/build/mp-weixin'),
  privateKeyPath: path.resolve('./private.key'),
  ignores: ['node_modules/**/*']
})

;(async () => {
  try {
    const uploadResult = await ci.upload({
      project,
      version: process.env.VERSION || '1.0.0',
      desc: process.env.DESC || '自动构建部署',
      setting: {
        es6: true,
        es7: true,
        minify: true,
        minifyJS: true,
        minifyWXML: true,
        minifyWXSS: true
      },
      onProgressUpdate: console.log
    })
    
    console.log('上传成功:', uploadResult)
  } catch (error) {
    console.error('上传失败:', error)
    process.exit(1)
  }
})()

5. 版本管理策略

package.json 版本控制

json 复制代码
json
{
  "name": "my-mini-program",
  "version": "1.0.0",
  "scripts": {
    "dev:mp": "uni -p mp-weixin",
    "build:mp": "uni build -p mp-weixin",
    "build:mp:test": "cross-env NODE_ENV=production UNI_PLATFORM=mp-weixin vue-cli-service uni-build --mode test",
    "build:mp:prod": "cross-env NODE_ENV=production UNI_PLATFORM=mp-weixin vue-cli-service uni-build --mode production",
    "upload:mp": "node scripts/upload.js"
  }
}

环境变量配置

ini 复制代码
bash
# .env.development
VUE_APP_API_BASE_URL=https://dev-api.example.com

# .env.test
VUE_APP_API_BASE_URL=https://test-api.example.com

# .env.production
VUE_APP_API_BASE_URL=https://api.example.com

6. 自动化测试集成

单元测试配置

java 复制代码
javascript
// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
  moduleFileExtensions: ['js', 'ts', 'vue'],
  transform: {
    '^.+\.vue$': '@vue/vue3-jest',
    '^.+\.(t|j)sx?$': 'babel-jest'
  },
  testMatch: ['**/tests/unit/**/*.spec.(js|ts)|**/__tests__/*.(js|ts)'],
  collectCoverageFrom: [
    'src/**/*.{js,ts,vue}',
    '!src/main.js',
    '!src/App.vue'
  ]
}

E2E 测试配置

dart 复制代码
javascript
// tests/e2e/specs/test.js
describe('微信小程序测试', () => {
  beforeAll(async () => {
    // 启动微信开发者工具
  })

  it('应该能够正常启动', async () => {
    // 测试逻辑
  })
})

7. 发布流程详解

手动发布步骤

  1. 代码检查

    arduino 复制代码
    bash
    npm run lint
    npm run test
  2. 构建打包

    arduino 复制代码
    bash
    npm run build:mp:prod
  3. 本地预览

    shell 复制代码
    bash
    # 使用微信开发者工具打开 dist/build/mp-weixin 目录
  4. 上传代码

    arduino 复制代码
    bash
    npm run upload:mp
  5. 提交审核

    • 登录微信公众平台
    • 进入小程序管理后台
    • 选择刚上传的版本
    • 填写版本说明和更新内容
    • 提交审核

自动化发布流程

css 复制代码
mermaid
graph TD
    A[代码提交] --> B{是否为Release分支}
    B -->|是| C[触发CI/CD]
    B -->|否| D[仅构建测试]
    C --> E[安装依赖]
    E --> F[构建小程序]
    F --> G[运行测试]
    G --> H[上传到微信]
    H --> I[发送通知]
    I --> J[等待审核]

8. 监控与回滚

错误监控

javascript 复制代码
javascript
// utils/errorHandler.js
export function initErrorHandler() {
  // 全局错误捕获
  uni.onError((error) => {
    console.error('小程序错误:', error)
    // 上报错误到监控平台
  })
  
  // 页面不存在监听
  uni.onPageNotFound((res) => {
    console.warn('页面未找到:', res.path)
  })
}

版本回滚策略

  1. 保留最近5个历史版本
  2. 记录每个版本的变更日志
  3. 出现严重问题时快速回滚到上一稳定版本

9. 最佳实践建议

代码规范

  1. 使用 ESLint + Prettier 统一代码风格
  2. 遵循 Git Commit 规范
  3. 定期进行 Code Review

性能优化

  1. 图片压缩和懒加载
  2. 分包加载策略
  3. 减少 setData 调用次数
  4. 合理使用缓存

安全考虑

  1. 敏感信息通过环境变量管理
  2. 接口请求使用 HTTPS
  3. 用户隐私数据保护

这套完整的流水线可以帮助你自动化构建、测试和发布 UniApp 微信小程序,提高开发效率和发布质量。

相关推荐
天空属于哈夫克31 天前
企业微信二次开发:精准实现关键词自动回复
架构·企业微信
子兮曰1 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰1 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万1 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝1 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋1 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
晨米酱1 天前
AGENTS.md:Agent 的上下文策略层
面试·架构·agent
这个DBA有点耶1 天前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
卡布鲁1 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
码流子1 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构