※前提条件:vue3 的uniapp开发
在 C 语言中,通过 #ifdef、#ifndef 的方式,为 windows、mac 等不同 os 编译不同的代码。 uni-app 参考这个思路,为 uni-app 提供了条件编译手段,在一个工程里优雅的完成了平台个性化实现。
runtime不是运行在电脑开发环境,而是运行在真正的终端上。
uni-app在每个平台(Web、Android App、iOS App、各家小程序)都有各自的runtime。这是一个比较庞大的工程。
条件编译是用特殊的注释作为标记,在编译时根据这些特殊的注释,将注释里面的代码编译到不同平台。
写法:以 #ifdef 或 #ifndef 加 %PLATFORM% 开头,以 #endif 结尾。
| 条件编译写法 | 说明 |
| #ifdef APP-PLUS 需条件编译的代码 #endif | 仅出现在 App 平台下的代码 |
| #ifndef H5 需条件编译的代码 #endif | 除了 H5 平台,其它平台均存在的代码 |
| #ifdef H5 || MP-WEIXIN 需条件编译的代码 #endif | 在 H5 平台或微信小程序平台存在的代码(这里只有||,不可能出现&&,因为没有交集) |
| 值 | 平台 |
| APP-PLUS | App |
| APP-PLUS-NVUE或APP-NVUE | App nvue |
| H5 | H5 |
| MP-WEIXIN | 微信小程序 |
| MP-ALIPAY | 支付宝小程序 |
| MP-BAIDU | 百度小程序 |
| MP-TOUTIAO | 字节跳动小程序 |
| MP-QQ | QQ小程序 |
| MP-360 | 360小程序 |
| MP | 微信小程序/支付宝小程序/百度小程序/字节跳动小程序/QQ小程序/360小程序 |
| QUICKAPP-WEBVIEW | 快应用通用(包含联盟、华为) |
|QUICKAPP-WEBVIEW-UNION|快应用联盟
<!-- #ifdef MP-WEIXIN --> <ad unit-id="123456789"></ad> <!-- #endif -->
在 CSS 中使用条件编译,往往是因为某些平台的内置组件的样式,会影响到一血界面的渲染。
/* #ifdef MP-ALIPAY*/
input {
padding: 0;
/* #endif */
}
// #ifdef APP-PLUS const uuid = plus.device.uuid; // #endif
{
"globalStyle": {
"navigationBarBackgroundColor": "#FF3333"
},
"pages": [{
"path": "pages/index/index"
}
// #ifdef APP-PLUS
, {
"path": "pages/speech/speech"
}
// #endif
]
}
Comment: