Loading

uni-app 条件编译是什么?

 uni-app 中的条件编译,指的是在编译阶段,通过特定的注释标记,根据不同平台(如小程序、App、H5 等)将对应注释块内的代码编译到指定平台,从而实现一套代码,多端差异化输出。这能有效解决跨端开发时的平台差异问题,避免运行时的冗余判断。比如:我在微信小程序上输出红色按钮,在h5或app上面输出蓝色按钮,那么条件编译就可以帮助你实现哦!

下面是一个条件编译在不同文件中使用的简要表格概括:

文件类型 条件编译写法 备注
JavaScript // #ifdef %PLATFORM% ... // #endif  
Template <!-- #ifdef %PLATFORM% --> ... <!-- #endif -->  
CSS /* #ifdef %PLATFORM% */ ... /* #endif */ 必须使用 /* */ 注释语法
Pages.json // #ifdef %PLATFORM% ... // #endif 需注意 JSON 格式的正确性

🛠️ 条件编译语法与平台标识符

条件编译以 #ifdef(如果已定义,即仅在指定平台存在)或 #ifndef(如果未定义,即除了指定平台外均存在)加平台标识符开头,以 #endif 结尾。

常见平台标识符(%PLATFORM%)及其含义

平台标识符 对应平台
APP-PLUS App
APP-PLUS-NVUE App nvue 页面
H5 H5
MP-WEIXIN 微信小程序
MP-ALIPAY 支付宝小程序
MP-BAIDU 百度小程序
MP-TOUTIAO 字节跳动小程序
MP-QQ QQ 小程序
MP 所有小程序平台
QUICKAPP-WEBVIEW 快应用通用

多平台可以使用 || 来连接,例如 #ifdef H5 || MP-WEIXIN 表示在 H5 平台或微信小程序平台存在。但不支持 && 操作符,因为没有交集。

📝 不同文件中的使用示例

1. JavaScript / <script> 中的条件编译

用于平台特定的逻辑或 API 调用。

// #ifdef H5
console.log('这段代码只在 H5 平台出现');
// 可以在 H5 平台执行特定的 API 调用或逻辑
// #endif

// #ifndef MP-WEIXIN
console.log('这段代码在除了微信小程序之外的平台都会出现');
// #endif

// #ifdef APP-PLUS || MP-WEIXIN
console.log('这段代码在 App 和微信小程序平台出现');
uni.getLocation({ // 假设 App 和微信小程序都用 uni.getLocation
  success: function (res) {
    console.log('获取位置成功');
  }
});
// #endif

2. Template / <template> 中的条件编译

用于控制不同平台显示的组件或元素。

<view>
  <text>所有平台都显示的内容</text>
  
  <!-- #ifdef H5 -->
  <view>只在 H5 平台显示的视图</view>
  <!-- 例如 H5 特有的广告组件 -->
  <!-- #endif -->
  
  <!-- #ifdef MP-WEIXIN -->
  <view>只在微信小程序平台显示的视图</view>
  <!-- 例如微信小程序特有的开放能力组件,如 official-account -->
  <official-account></official-account>
  <!-- #endif -->
  
  <!-- #ifndef APP-PLUS -->
  <view>在非 App 平台(如 H5、小程序)显示的视图</view>
  <!-- #endif -->
</view>

3. CSS / <style> 中的条件编译

用于编写平台特定的样式。注意:必须使用 /* */ 注释语法

.common-style {
  font-size: 14px;
}

/* #ifdef H5 */
.h5-specific-style {
  /* 只在 H5 平台生效的样式 */
  color: blue;
}
/* #endif */

/* #ifdef MP-WEIXIN */
.wx-specific-style {
  /* 只在微信小程序平台生效的样式 */
  padding: 10rpx;
}
/* #endif */

4. Pages.json 中的条件编译

用于配置平台特定的页面路由、窗口样式、选项卡栏等。需特别注意 JSON 格式的正确性,避免出现多余的逗号。

{
  "pages": [
    {
      "path": "pages/common/index",
      "style": {
        "navigationBarTitleText": "通用页面"
      }
    },
    // #ifdef H5
    {
      "path": "pages/h5/specific",
      "style": {
        "navigationBarTitleText": "H5特有页面",
        "enablePullDownRefresh": true
      }
    },
    // #endif
    // #ifdef MP-WEIXIN
    {
      "path": "pages/wx/specific",
      "style": {
        "navigationBarTitleText": "微信特有页面",
        "usingComponents": {}
      }
    }
    // #endif
  ],
  // #ifndef MP-WEIXIN
  "globalStyle": {
    "navigationBarTextStyle": "black",
    "navigationBarTitleText": "非微信小程序全局样式",
    "backgroundColor": "#F8F8F8"
  },
  // #endif
  // #ifdef MP-WEIXIN
  "tabBar": {
    "color": "#7A7E83",
    "selectedColor": "#3cc51f",
    "borderStyle": "black",
    "backgroundColor": "#ffffff",
    "list": [{
      "pagePath": "pages/index/index",
      "iconPath": "static/image/icon.png",
      "selectedIconPath": "static/image/iconHL.png",
      "text": "首页"
    }]
  }
  // #endif
}

5. Static 目录的条件编译

static 目录下可以建立与平台标识符同名的子目录(字母均为小写),该子目录下的静态资源只有在特定平台才会被编译进去。

例如,目录结构如下:

└─static
    ├─mp-weixin
    │   └─wx-specific-image.png
    ├─h5
    │   └─h5-specific-image.png
    └─common-image.png
  • common-image.png 在所有平台都会被编译。

  • wx-specific-image.png 只在微信小程序平台被编译。

  • h5-specific-image.png 只在 H5 平台被编译。

在代码中引用时,无需在路径中指定平台目录:

<image src="/static/common-image.png"></image>
<image src="/static/wx-specific-image.png"></image> <!-- 微信小程序平台编译时,会找到 mp-weixin 目录下的资源 -->

⚠️ 注意事项

  1. 注释语法必须正确

    • JS 中使用 // 注释

    • CSS 中使用 /* 注释 */

    • Vue 模板中使用 <!-- 注释 -->

  2. 保持语法正确性:条件编译无论是否生效,都必须保证编译前后文件的语法正确性

    • 在 JSON 中(如 pages.json),要特别注意逗号问题,避免出现多余的逗号导致 JSON 解析错误。

    • 在 JS 中,避免条件编译导致重复导入模块。

  3. 平台标识符大小写:平台标识符是区分大小写的,例如 MP-WEIXIN 不能写成 mp-weixin 或 MP-WeiXin

  4. APP-PLUS 与 APP-NVUEAPP-PLUS 包含 App 下的 nvue 和 vue 页面,而 APP-PLUS-NVUE  APP-NVUE 仅针对 App 的 nvue 页面。

  5. 未定义平台名称:如果使用了未定义(可能是拼写错误或低版本 HBuilderX 不支持)的平台名称,#ifdef 中的代码不会生效,而 #ifndef 中的代码会生效。

  6. Android 和 iOS 的平台区分:条件编译不能直接用于区分 Android 和 iOS 平台。如果需要区分,请在运行时通过 uni.getSystemInfo API 获取 platform 信息来进行判断。

💡 实战建议

  • 按需使用:虽然条件编译很强大,但不应过度使用。优先考虑使用 uni-app 提供的跨端 API 和组件。只有当它们无法满足平台差异化需求时,再使用条件编译。

  • 代码组织:对于大量平台特定的代码,可以考虑将其放入不同的平台专用目录(如 platforms 目录),或者利用 static 目录的条件编译特性来管理平台特定的静态资源。

  • 充分测试:由于条件编译后的代码只在特定平台出现,务必在所有目标平台上进行充分的测试,以确保功能和样式的一致性。

🧪 一个简单的综合案例

假设我们需要开发一个功能:

  • 在 H5 平台,显示一个蓝色按钮,并调用浏览器控制台日志。

  • 微信小程序平台,显示一个绿色按钮,并调用微信的登录接口。

  • App平台,显示一个红色按钮。

  • 其他平台显示默认按钮。

<template>
  <view>
    <!-- 所有平台都显示的视图 -->
    <text>欢迎使用uni-app</text>

    <!-- 平台特定的按钮 -->
    <!-- #ifdef H5 -->
    <button class="h5-btn" @click="h5Method">H5按钮</button>
    <!-- #endif -->

    <!-- #ifdef MP-WEIXIN -->
    <button class="wx-btn" @click="wxMethod">微信按钮</button>
    <!-- #endif -->

    <!-- #ifdef APP-PLUS -->
    <button class="app-btn" @click="appMethod">App按钮</button>
    <!-- #endif -->

    <!-- #ifndef H5 || MP-WEIXIN || APP-PLUS -->
    <button class="default-btn">默认按钮</button>
    <!-- #endif -->
  </view>
</template>

<script>
export default {
  methods: {
    // H5 平台方法
    // #ifdef H5
    h5Method() {
      console.log('这是H5平台的方法');
    },
    // #endif

    // 微信小程序平台方法
    // #ifdef MP-WEIXIN
    wxMethod() {
      wx.login({
        success(res) {
          console.log(res.code);
        }
      });
    },
    // #endif

    // App 平台方法
    // #ifdef APP-PLUS
    appMethod() {
      uni.showToast({
        title: 'App按钮被点击'
      });
    }
    // #endif
  }
}
</script>

<style>
/* 公共样式 */
button {
  margin: 10px;
  padding: 10px;
}

/* H5 平台样式 */
/* #ifdef H5 */
.h5-btn {
  background-color: blue;
  color: white;
}
/* #endif */

/* 微信小程序平台样式 */
/* #ifdef MP-WEIXIN */
.wx-btn {
  background-color: green;
  color: white;
}
/* #endif */

/* App 平台样式 */
/* #ifdef APP-PLUS */
.app-btn {
  background-color: red;
  color: white;
}
/* #endif */
</style>

 

posted @ 2025-09-02 23:03  Carvers  阅读(69)  评论(0)    收藏  举报