uniapp如何判断当前环境
判断当前运行环境
在uniapp中,可以通过uni.getSystemInfoSync()或uni.getSystemInfo()获取系统信息,从而判断当前运行的环境。系统信息中包含platform字段,用于标识当前运行平台。
const systemInfo = uni.getSystemInfoSync();
console.log(systemInfo.platform); // 输出当前平台
常见的平台值
platform字段可能返回以下值:
"android":Android平台"ios":iOS平台"devtools":微信开发者工具"windows":Windows平台"mac":Mac平台
判断H5环境
在H5环境下,可以通过window对象判断:
const isH5 = typeof window !== 'undefined' && window.location;
console.log(isH5); // true表示H5环境
判断小程序环境
通过uni.getSystemInfoSync()的uniPlatform字段或process.env.UNI_PLATFORM判断:
const isMiniProgram = process.env.UNI_PLATFORM === 'mp-weixin';
console.log(isMiniProgram); // true表示微信小程序
环境变量判断
uniapp提供了全局变量process.env,可以用于判断当前编译环境:
console.log(process.env.NODE_ENV); // 开发或生产环境
console.log(process.env.UNI_PLATFORM); // 平台类型
条件编译
uniapp支持条件编译,可在代码中根据平台编写不同逻辑:
// #ifdef H5
console.log('H5平台');
// #endif
// #ifdef MP-WEIXIN
console.log('微信小程序');
// #endif
封装环境判断函数
可以封装一个通用函数用于判断环境:
function getEnv() {
const systemInfo = uni.getSystemInfoSync();
if (systemInfo.platform === 'devtools') return 'devtools';
if (systemInfo.platform === 'android') return 'android';
if (systemInfo.platform === 'ios') return 'ios';
if (typeof window !== 'undefined') return 'h5';
return 'unknown';
}





