development.md 8.1 KB

开发指南

环境搭建

必需软件

  1. HBuilderXVisual Studio Code
  2. 微信开发者工具 (开发微信小程序时)
  3. Android Studio (开发 App 时)
  4. Xcode (开发 iOS App 时,仅 macOS)

Node.js 环境

# 检查 Node.js 版本
node -v  # 需要 >= 12

# 检查 npm 版本
npm -v

# 安装依赖
npm install
# 或使用 yarn
yarn install

项目配置

环境配置

修改 common/config.js 配置不同环境:

// 生产环境
export const apiBaseUrl = 'https://backend.qicai321.com';

// 测试环境
export const apiBaseUrl = 'http://192.168.66.187:8083';

微信小程序配置

manifest.json 中配置小程序 AppID:

{
  "mp-weixin": {
    "appid": "wxc9655eeaa3223b75",
    "setting": {
      "urlCheck": false
    }
  }
}

开发流程

1. 启动开发服务器

# H5 开发
npm run dev:h5

# 微信小程序开发
npm run dev:mp-weixin

# App 开发 (需要在 HBuilderX 中运行)

2. 页面开发

创建新页面的步骤:

  1. 创建页面文件

pages 目录下创建新的目录和 .vue 文件:

   pages/
     new-page/
       new-page.vue
  1. 配置页面路由

pages.json 中添加页面配置:

   {
     "path": "pages/new-page/new-page",
     "style": {
       "navigationBarTitleText": "新页面"
     }
   }
  1. 页面跳转

    // 保留当前页面,跳转到应用内的某个页面
    uni.navigateTo({
     url: '/pages/new-page/new-page'
    });
       
    // 关闭当前页面,跳转到应用内的某个页面
    uni.redirectTo({
     url: '/pages/new-page/new-page'
    });
       
    // 跳转到 tabBar 页面
    uni.switchTab({
     url: '/pages/index/index'
    });
    

3. API 调用

使用封装的 API

// 方式一:直接导入
import { getUserInfo } from '@/api/user.js';

export default {
  methods: {
    async fetchData() {
      try {
        const userInfo = await getUserInfo();
        console.log(userInfo);
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    }
  }
}

使用 Composition API

import { useUserApi } from '@/composables/useUserApi.js';

export default {
  setup() {
    const { fetchUserInfo, loading, error } = useUserApi();
    
    const loadData = async () => {
      try {
        const data = await fetchUserInfo();
        console.log(data);
      } catch (err) {
        console.error(error.value);
      }
    };
    
    return {
      loadData,
      loading,
      error
    };
  }
}

4. 样式开发

使用 rpx 单位

uni-app 使用 rpx 作为响应式单位:

/* 750rpx 等于屏幕宽度,自适应不同屏幕 */
.container {
  width: 750rpx;
  height: 200rpx;
  padding: 20rpx;
}

常用样式类

/* 弹性布局 */
.flex {
  display: flex;
}

.flex-column {
  flex-direction: column;
}

/* 居中对齐 */
.center {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 按钮样式 */
.btn-primary {
  background-color: #0039b3;
  color: #fff;
  border-radius: 44rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
}

调试技巧

1. 控制台调试

// 在页面中使用
console.log('调试信息', data);
console.error('错误信息', error);
console.warn('警告信息', warning);

2. 条件编译

针对不同平台开发:

// #ifdef APP-PLUS
console.log('App 平台');
// #endif

// #ifdef MP-WEIXIN
console.log('微信小程序');
// #endif

// #ifdef H5
console.log('H5 平台');
// #endif

3. 真机调试

App 真机调试:

  1. 连接手机到电脑
  2. 在 HBuilderX 中选择 "运行" → "运行到手机或模拟器"
  3. 选择设备并运行

微信小程序调试:

  1. 在微信开发者工具中打开项目
  2. 点击 "预览" 或 "真机调试"
  3. 使用微信扫码在手机上查看

4. 网络请求调试

查看网络请求:

// 在 utils/request.js 中已有 console.log
console.log('request:', options);
console.log('response:', response);

使用抓包工具:

  • Charles/Fiddler: 抓取 HTTP/HTTPS 请求
  • 微信开发者工具: 查看小程序网络请求

构建部署

构建 H5

npm run build:h5

构建产物在 unpackage/dist/build/h5

构建微信小程序

npm run build:mp-weixin

构建产物在 unpackage/dist/build/mp-weixin

构建 App

  1. 在 HBuilderX 中选择 "发行" → "原生 App-云打包"
  2. 配置打包参数
  3. 提交打包

常见问题

1. 页面跳转失败

问题: 跳转后白屏或报错

解决方案:

  • 检查页面路径是否正确
  • 检查 pages.json 配置是否正确
  • 检查页面文件是否存在语法错误

2. API 请求失败

问题: 网络请求返回 404 或 500

解决方案:

  • 检查 API 地址是否正确
  • 检查网络连接
  • 检查后端服务是否正常
  • 查看控制台错误信息

3. 样式不生效

问题: CSS 样式显示不正确

解决方案:

  • 检查选择器是否正确
  • 使用 !important 提高优先级
  • 检查 scoped 是否影响样式
  • 使用 rpx 而非 px

4. 真机调试问题

问题: 真机上无法正常运行

解决方案:

  • 检查手机是否允许 USB 调试
  • 检查防火墙设置
  • 尝试重启调试工具
  • 查看真机运行日志

5. Token 过期

问题: 请求返回 401 未授权

解决方案:

  • 清除本地 token: uni.removeStorageSync('token')
  • 重新登录获取新 token
  • 添加全局请求拦截器处理 token 刷新

代码规范

命名规范

  1. 变量命名: 使用驼峰命名法

    const userName = 'John';
    const isLogin = true;
    
  2. 方法命名: 使用动词开头

    function getUserInfo() {}
    function handleLogin() {}
    function fetchData() {}
    
  3. 组件命名: 使用 PascalCase

    <UserInfo />
    <VoiceCheckModal />
    

文件结构

pages/
  page-name/
    page-name.vue     # 页面文件
    page-name.js      # 页面逻辑(如果复杂)
    page-name.scss    # 页面样式(如果复杂)

注释规范

/**
 * 获取用户信息
 * @param {Number} userId - 用户ID
 * @returns {Promise} - 用户信息
 */
export function getUserInfo(userId) {
  // 实现代码
}

版本管理

Git 工作流

# 创建新分支
git checkout -b feature/new-feature

# 提交代码
git add .
git commit -m "feat: 添加新功能"

# 推送分支
git push origin feature/new-feature

提交信息规范

  • feat: 新功能
  • fix: 修复 bug
  • docs: 文档更新
  • style: 代码格式调整
  • refactor: 代码重构
  • test: 添加测试
  • chore: 构建过程或辅助工具的变动

性能优化

1. 图片优化

  • 使用压缩后的图片
  • 使用 WebP 格式(H5 平台)
  • 懒加载图片

2. 代码分割

// 按需加载组件
const Component = () => import('@/components/Component.vue');

3. 数据缓存

// 缓存 API 数据
const cachedData = uni.getStorageSync('cachedData');
if (cachedData) {
  // 使用缓存数据
} else {
  // 请求新数据
}

4. 防抖和节流

// 防抖
function debounce(func, wait) {
  let timeout;
  return function() {
    clearTimeout(timeout);
    timeout = setTimeout(func, wait);
  };
}

// 节流
function throttle(func, limit) {
  let inThrottle;
  return function() {
    if (!inThrottle) {
      func.apply(this, arguments);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

测试

单元测试

// 测试 API 方法
import { getUserInfo } from '@/api/user.js';

test('getUserInfo should return user data', async () => {
  const userInfo = await getUserInfo();
  expect(userInfo).toHaveProperty('id');
});

集成测试

  • 测试完整的用户流程
  • 测试页面跳转
  • 测试表单提交

真机测试

  • 在不同设备上测试
  • 测试不同网络环境
  • 测试边界情况