The conditional compilation mechanism
Conditional compilation is a capability provided by uni-app that enables dynamic code compilation based on platforms, environments, or custom conditions. It allows developers to write differentiated logic for different platforms or scenarios within the same codebase, thereby avoiding the complexity of maintaining multiple code repositories.
Basic Syntax of Conditional Compilation
uni-app's conditional compilation uses special comment syntax, available in both single-line and multi-line forms:
// #ifdef PlatformName
Platform-specific code
// #endif
/* #ifdef PlatformName */
Platform-specific code
/* #endif */
Common platform identifiers include:
H5
: Web platformMP-WEIXIN
: WeChat Mini ProgramAPP
: App platformVUE3
: Vue 3 projects
Platform Conditional Compilation Examples
Handling Styles for Different Platforms
/* Only takes effect on the H5 platform */
/* #ifdef H5 */
.header {
height: 88px;
}
/* #endif */
/* WeChat Mini Program-specific styles */
/* #ifdef MP-WEIXIN */
.header {
height: 64rpx;
}
/* #endif */
Platform-Specific Components
<template>
<!-- Universal component -->
<view class="container">
<!-- Only displayed in Mini Programs -->
<!-- #ifdef MP-WEIXIN -->
<ad unit-id="123"></ad>
<!-- #endif -->
<!-- Only displayed in App -->
<!-- #ifdef APP -->
<native-ad></native-ad>
<!-- #endif -->
</view>
</template>
Environment Conditional Compilation
In addition to platform differentiation, conditional compilation can also be based on the development environment:
// #ifdef DEVELOPMENT
console.log('Debug information');
// #endif
// #ifdef PRODUCTION
// No log output in production
// #endif
Custom Conditional Compilation
uni-app supports defining custom conditions via process.env.UNI_CUSTOM
:
// vue.config.js
module.exports = {
configureWebpack: {
plugins: [
new webpack.DefinePlugin({
'process.env.UNI_CUSTOM': JSON.stringify({
'CUSTOM_FEATURE': true
})
})
]
}
}
Usage example:
// #ifdef CUSTOM_FEATURE
console.log('Enable custom feature');
// #endif
Complex Condition Combinations
Supports combining multiple conditions using logical operators:
// Both WeChat Mini Program and development environment
// #ifdef MP-WEIXIN && DEVELOPMENT
wx.showToast({
title: 'Development Debugging'
})
// #endif
// Satisfy any condition
// #ifdef H5 || APP
console.log('Running on H5 or App platform');
// #endif
Nested Conditional Compilation
Conditional compilation supports multi-level nesting for complex scenarios:
// #ifdef MP-WEIXIN
// #ifdef DEVELOPMENT
const baseURL = 'https://dev.api.com'
// #else
const baseURL = 'https://api.com'
// #endif
// #elif H5
const baseURL = '/api'
// #endif
Using Conditional Compilation in Scripts
JavaScript/TypeScript also supports conditional compilation:
function getPlatform() {
// #ifdef H5
return 'web'
// #endif
// #ifdef MP-WEIXIN
return 'wechat'
// #endif
// #ifdef APP
return 'app'
// #endif
}
Notes on Conditional Compilation
-
Scope Limitation: Variables declared within a conditional compilation block are not accessible outside.
// #ifdef H5 const h5Var = 'h5' // Only exists on the H5 platform // #endif console.log(h5Var) // Will cause errors on other platforms
-
Syntax Integrity: Each conditional block must fully contain the syntax structure.
// Incorrect example function test() { // #ifdef H5 return 'h5' } // #endif
-
Preprocessing Feature: Conditional compilation is processed before code minification and differs from runtime condition checks.
Combining Conditional Compilation with Dynamic Imports
Can be combined with dynamic imports to load modules by platform:
// #ifdef H5
import('./h5-module.js').then(module => {
module.init()
})
// #endif
// #ifdef MP-WEIXIN
import('./wechat-module.js').then(module => {
module.init()
})
// #endif
Performance Optimization with Conditional Compilation
Proper use of conditional compilation can significantly optimize bundle size:
- Exclude components for unused platforms.
- Remove platform-independent polyfills.
- Avoid bundling unused third-party libraries.
// #ifndef H5
// Use lightweight date library on non-H5 platforms
import dayjs from 'dayjs'
// #endif
// #ifdef H5
// Use full moment.js on H5 platform
import moment from 'moment'
// #endif
Debugging Tips for Conditional Compilation
-
View preprocessing results:
# View preprocessing results for the H5 platform npx cross-env UNI_PLATFORM=h5 vue-cli-service uni-build --watch
-
Use environment variables for debugging:
// Temporarily enable debug mode // #ifdef DEBUG || DEVELOPMENT console.log('Debug information') // #endif
Advanced Usage of Conditional Compilation
Platform Feature Detection
function useFeature() {
// #ifdef MP-WEIXIN
if (wx.canIUse('feature-name')) {
return true
}
// #endif
// #ifdef APP
return uni.getSystemInfoSync().platform === 'ios'
// #endif
return false
}
Multi-Platform Compatible Components
<template>
<view>
<!-- #ifdef H5 -->
<button @click="handleClick">HTML Button</button>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<button @click="handleClick" size="mini">Mini Program Button</button>
<!-- #endif -->
</view>
</template>
Combining CSS Variables with Conditional Compilation
:root {
/* #ifdef H5 */
--primary-color: #1890ff;
/* #endif */
/* #ifdef MP-WEIXIN */
--primary-color: #07C160;
/* #endif */
}
.button {
background-color: var(--primary-color);
}
Engineering Practices for Conditional Compilation
-
Directory Structure Organization:
/src /platform /h5 index.js /mp-weixin index.js App.vue
-
Automated Platform Detection:
// platform.js export function getApiBase() { // #ifdef H5 return '/api' // #endif // #ifdef MP-WEIXIN return 'https://wechat.api.com' // #endif }
-
Build Configuration Extension:
// vue.config.js module.exports = { chainWebpack(config) { // #ifdef H5 config.plugin('html').tap(args => { args[0].title = 'H5 Exclusive Title' return args }) // #endif } }
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:跨平台编译原理