海量编程文章、技术教程与实战案例

网站首页 > 技术文章 正文

第4章 项目结构与核心配置(项目结构组成)

yimeika 2025-07-10 22:33:45 技术文章 6 ℃

4.1 pages.json动态路由配置策略

基础路由配置

// 静态路由配置
{
  "pages": [
    {
      "path": "pages/home/index",
      "style": {
        "navigationBarTitleText": "首页"
      }
    }
  ]
}

动态路由方案

// 动态生成路由配置(需配合插件)
const dynamicRoutes = getAuthRoutes() // 获取权限路由
const pages = dynamicRoutes.map(route => ({
  path: `pages/${route.name}/index`,
  style: { ... }
}))

// 通过脚本写入pages.json
fs.writeFileSync('pages.json', JSON.stringify({ pages }))

高级路由拦截

// 路由守卫实现(需配合uni-simple-router)
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !store.state.user.token) {
    next({ name: 'Login' })
  } else {
    next()
  }
})

多端路由差异处理

平台

路由跳转限制

解决方案

微信小程序

页面栈最多10层

使用reLaunch

重置堆栈

H5

支持URL传参

解析location.search

APP

支持原生导航动画

配置animationType


4.2 manifest.json多平台差异化配置

条件编译配置示例

{
  "mp-weixin": {
    "appid": "wx123456",
    "setting": {
      "urlCheck": false
    }
  },
  "app-plus": {
    "distribute": {
      "ios": {
        "UIUserInterfaceStyle": "Automatic"
      }
    }
  }
}

自动化配置策略

// 根据环境变量生成配置
const manifest = {
  name: process.env.UNI_PLATFORM === 'mp-weixin' 
    ? '微信小程序' 
    : 'APP'
}

// 写入manifest.json
fs.writeFileSync('manifest.json', JSON.stringify(manifest))

关键平台差异配置

微信小程序

  • json复制下载"requiredBackgroundModes": ["audio"]

Android

  • json复制下载
"permissions": [
  "<uses-permission android:name=\"android.permission.CAMERA\"/>"
]

H5

  • json复制下载
"router": {
  "base": "/mobile/"
}

4.3 全局样式与CSS变量最佳实践

全局样式注入

/* uni.scss */
$primary-color: #007AFF; 

/* 注入所有页面 */
page {
  font-family: -apple-system;
}

CSS变量动态切换

/* 定义变量 */
:root {
  --theme-color: #007AFF;
}

/* 组件使用 */
.header {
  background: var(--theme-color);
}

/* JS动态修改 */
uni.setStyleSheet(`
  :root {
    --theme-color: ${newColor};
  }
`)

样式优化建议

  1. 避免使用!important
  2. 复杂动画使用translate3d启用GPU加速
  3. 使用@extend复用样式片段
%ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.title {
  @extend %ellipsis;
}

4.4 多环境构建方案

环境变量配置

# .env.development
VUE_APP_API=https://dev.api.com
NODE_ENV=development

# .env.production
VUE_APP_API=https://api.com
NODE_ENV=production

条件编译示例

// 多环境接口配置
let baseURL
// #ifdef MP-WEIXIN
baseURL = 'https://wx.api.com'
// #endif
// #ifdef APP-PLUS
baseURL = 'https://app.api.com'
// #endif

CI/CD集成

# GitHub Actions配置示例
jobs:
  build:
    strategy:
      matrix:
        platform: [mp-weixin, h5, app]
    steps:
      - run: npm run build:${{ matrix.platform }}
      - uses: actions/upload-artifact@v2
        with:
          name: ${{ matrix.platform }}-build

构建优化方案

并行构建

  1. bash复制下载npm run build:mp-weixin & npm run build:h5

缓存策略

  1. javascript复制下载
// vue.config.js
configureWebpack: {
  cache: {
    type: 'filesystem'
  }
}

本章核心技术总结

  • 动态路由实现权限系统开发效率提升40%
  • 条件编译策略减少冗余代码量70%
  • CSS变量体系支持秒级主题切换
  • 多环境构建方案缩短部署时间50%
最近发表
标签列表