Skip to content

条件注释实现跨端兼容

条件编译是用特殊的注释作为标记,在编译时根据这些特殊的注释,将注释里面的代码编译到不同平台。

写法: 以 #ifdef 加平台标识 开头,以 #endif 结尾。

js
#ifdef H5
  console.log('这是一个H5页面');
#endif

常见平台标识

平台参考文档
APP-PLUS5+APPHTML5+规范
H5H5
MP-WEIXIN微信小程序微信小程序
MP-ALIPAY支付宝小程序支付宝小程序
MP-BAIDU百度小程序百度小程序
MP-TOUTIAO头条小程序头条小程序
MP-QQQQ 小程序QQ 小程序

组件的条件注释

  • 代码演示
html
<!-- #ifdef H5 -->
<view> h5页面会显示 </view>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<view> 微信小程序会显示 </view>
<!-- #endif -->
<!-- #ifdef APP-PLUS -->
<view> app会显示 </view>
<!-- #endif -->

api 的条件注释

  • 代码演示
js
onLoad () {
  //#ifdef MP-WEIXIN
  console.log('微信小程序')
  //#endif
  //#ifdef H5
  console.log('h5页面')
  //#endif
}
  • 样式的条件注释
js
/* #ifdef H5 */
view {
  height: 100px;
  line-height: 100px;
  background: red;
}
/* #endif */
/* #ifdef MP-WEIXIN */
view {
  height: 100px;
  line-height: 100px;
  background: green;
}
/* #endif */