Conditional compilation for multi-platform adaptation
Conditional Compilation for Multi-Platform Adaptation
The conditional compilation feature in uni-app allows developers to write platform-specific code within a single codebase, enabling multi-platform adaptation. Using special comment syntax, code blocks can be selectively retained or removed during the compilation phase, addressing API differences and style compatibility issues across platforms.
Basic Syntax of Conditional Compilation
Conditional compilation uses // #ifdef
and // #endif
as the basic syntax structure, with platform identifiers inserted in between:
// #ifdef H5
console.log('This code appears only on the H5 platform');
// #endif
// #ifdef MP-WEIXIN
console.log('This code appears only on the WeChat Mini Program platform');
// #endif
Common platform identifiers include:
H5
: Web browser environmentMP-WEIXIN
: WeChat Mini ProgramMP-ALIPAY
: Alipay Mini ProgramAPP
: Native App environmentAPP-PLUS
: Includes App and H5APP-NVUE
: App nvue pages
Multi-Conditional Combinations
Complex conditions can be combined using ||
and &&
:
// #ifdef H5 || MP-WEIXIN
console.log('H5 or WeChat Mini Program environment');
// #endif
// #ifdef APP && IOS
console.log('iOS native environment only');
// #endif
Negation conditions use #ifndef
:
// #ifndef MP-ALIPAY
console.log('Non-Alipay Mini Program environment');
// #endif
Conditional Compilation in Style Files
Conditional compilation is also supported in style
tags to handle platform-specific style differences:
<style>
/* #ifdef H5 */
.container {
padding: 20px;
}
/* #endif */
/* #ifdef MP-WEIXIN */
.container {
padding: 10rpx;
}
/* #endif */
</style>
Conditional Compilation in Templates
Template structures can also be differentiated using conditional compilation:
<template>
<view>
<!-- #ifdef H5 -->
<h1>Web Title</h1>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<view class="wx-title">Mini Program Title</view>
<!-- #endif -->
</view>
</template>
Conditional Compilation in Configuration Files
pages.json
can include platform-specific configurations for routing and other parameters:
{
"pages": [
{
"path": "pages/index",
"style": {
"navigationBarTitleText": "Home",
// #ifdef H5
"titleNView": false
// #endif
}
}
]
}
Practical Use Case Examples
Platform-Specific Component Loading
// #ifdef H5
import H5Video from './h5-video.vue';
// #endif
// #ifdef MP-WEIXIN
import WxVideo from './wx-video.vue';
// #endif
export default {
components: {
// #ifdef H5
'my-video': H5Video,
// #endif
// #ifdef MP-WEIXIN
'my-video': WxVideo
// #endif
}
}
Handling API Differences
function getSystemInfo() {
// #ifdef H5
return {
screenWidth: window.innerWidth,
platform: 'h5'
};
// #endif
// #ifdef MP-WEIXIN
return wx.getSystemInfoSync();
// #endif
// #ifdef APP
return plus.os.name;
// #endif
}
Dynamic Style Handling
<template>
<view :class="['container', platformClass]">
<!-- Content Area -->
</view>
</template>
<script>
export default {
computed: {
platformClass() {
// #ifdef H5
return 'h5-container';
// #endif
// #ifdef MP-WEIXIN
return 'wx-container';
// #endif
}
}
}
</script>
Advanced Usage: Custom Conditional Compilation
Custom conditions can be extended in vue.config.js
:
module.exports = {
configureWebpack: {
plugins: [
new webpack.DefinePlugin({
'process.env.UNI_PLATFORM': JSON.stringify(process.env.UNI_PLATFORM),
'process.env.CUSTOM_FLAG': '"YOUR_VALUE"'
})
]
}
}
Then use in code:
// #ifdef CUSTOM_FLAG
console.log('Custom conditional compilation activated');
// #endif
Limitations of Conditional Compilation
- Debugging Difficulty: Compiled code may not be directly debuggable in development tools.
- Code Redundancy: All platform-specific code exists in the source, potentially affecting readability.
- Lack of Dynamism: Content is determined at compile time and cannot be switched dynamically at runtime.
Performance Optimization Recommendations
- Avoid using extensive conditional compilation branches in frequently called functions.
- For complex platform differences, consider splitting into separate files:
// utils/h5.js
export function platformApi() { /* H5 implementation */ }
// utils/weixin.js
export function platformApi() { /* WeChat implementation */ }
// Main file
// #ifdef H5
import { platformApi } from './utils/h5';
// #endif
// #ifdef MP-WEIXIN
import { platformApi } from './utils/weixin';
// #endif
Integration with Cross-Platform Solutions
Conditional compilation can be combined with:
uni-app
built-in API differences smoothing- Third-party cross-platform libraries (e.g.,
taro
,remax
) - Custom runtime adaptation layers
// Adaptation layer example
function request(url, options) {
// #ifdef H5
return fetch(url, options);
// #endif
// #ifdef MP-WEIXIN
return new Promise((resolve, reject) => {
wx.request({
url,
...options,
success: resolve,
fail: reject
});
});
// #endif
}
Version Control and Conditional Compilation
Fine-grained control using version numbers:
// #ifdef H5 && VERSION > 2.0
console.log('H5 platform version above 2.0');
// #endif
Inject version variables in build commands:
cross-env VERSION=2.1 uni-build
Static Analysis and Code Inspection
Due to the impact of conditional compilation on code structure, it is recommended to:
- Use ESLint plugins to check conditional compilation syntax.
- Perform static analysis on platform-specific code separately in CI workflows.
- Establish platform-specific test case sets.
// Example test code
describe('H5-specific functionality', () => {
// #ifdef H5
it('should execute H5 method correctly', () => {
expect(h5Function()).toBeTruthy();
});
// #endif
});
Best Practices for Conditional Compilation
- Clear Comments: Add explanatory comments for each conditional block.
- Platform Detection: Retain runtime platform detection capabilities:
const isH5 = process.env.UNI_PLATFORM === 'h5';
const isWeixin = process.env.UNI_PLATFORM === 'mp-weixin';
- Directory Organization: Split large modules by platform:
src/
platforms/
h5/
components/
utils/
weixin/
components/
utils/
- Build Configuration: Generate multi-platform packages via different build commands:
{
"scripts": {
"build:h5": "uni-build --platform h5",
"build:wx": "uni-build --platform mp-weixin"
}
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn