mini-platform-小程序环境检测.md 5.0 KB


description: "小程序平台检测工具 - 用于识别当前运行平台环境"

小程序平台检测工具使用文档

功能概述

mini/src/utils/platform.ts 提供了一套完整的平台检测工具,用于在 Taro 跨端小程序中识别当前运行环境,支持微信小程序、H5 网页端等多种平台的条件判断。

导入方式

import { getPlatform, isWeapp, isH5 } from '@/utils/platform'

核心功能

1. 获取当前平台

getPlatform(): TaroGeneral.ENV_TYPE

返回当前运行环境的平台类型枚举值。

返回值说明:

  • WEAPP: 微信小程序
  • WEB: H5 网页端
  • RN: React Native
  • SWAN: 百度智能小程序
  • ALIPAY: 支付宝小程序
  • TT: 字节跳动小程序
  • QQ: QQ 小程序

使用示例:

import { getPlatform } from '@/utils/platform'
import Taro from '@tarojs/taro'

const currentPlatform = getPlatform()
console.log('当前平台:', currentPlatform)

// 根据平台执行不同逻辑
switch (currentPlatform) {
  case Taro.ENV_TYPE.WEAPP:
    // 微信小程序专属逻辑
    break
  case Taro.ENV_TYPE.WEB:
    // H5 网页端专属逻辑
    break
  default:
    // 其他平台通用逻辑
}

2. 是否为微信小程序

isWeapp(): boolean

判断当前是否在微信小程序环境中运行。

使用示例:

import { isWeapp } from '@/utils/platform'

if (isWeapp()) {
  // 微信小程序专属功能
  wx.login({
    success: (res) => {
      console.log('微信登录成功:', res.code)
    }
  })
  
  // 使用小程序 API
  wx.getUserProfile({
    desc: '用于完善用户资料',
    success: (res) => {
      console.log('用户信息:', res.userInfo)
    }
  })
} else {
  // 非小程序环境的替代方案
  console.log('当前不是微信小程序环境')
}

3. 是否为 H5 网页端

isH5(): boolean

判断当前是否在 H5 网页端环境中运行。

使用示例:

import { isH5 } from '@/utils/platform'

if (isH5()) {
  // H5 网页端专属功能
  // 使用浏览器 API
  localStorage.setItem('token', 'your-token')
  
  // 使用 DOM API
  window.addEventListener('resize', handleResize)
} else {
  // 小程序环境的替代方案
  Taro.setStorageSync('token', 'your-token')
}

实际应用场景

场景1:条件渲染组件

import { isWeapp, isH5 } from '@/utils/platform'

const PlatformSpecificButton = () => {
  if (isWeapp()) {
    return (
      <Button onClick={() => wx.navigateToMiniProgram({ appId: 'targetAppId' })}>
        打开其他小程序
      </Button>
    )
  }
  
  if (isH5()) {
    return (
      <Button onClick={() => window.open('https://example.com', '_blank')}>
        打开外部链接
      </Button>
    )
  }
  
  return null
}

场景2:平台差异化 API 调用

import { isWeapp, isH5 } from '@/utils/platform'

const uploadImage = async (file: File) => {
  if (isWeapp()) {
    // 小程序上传
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: '/api/upload',
        filePath: file.path,
        name: 'file',
        success: resolve,
        fail: reject
      })
    })
  }
  
  if (isH5()) {
    // H5 上传
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await fetch('/api/upload', {
      method: 'POST',
      body: formData
    })
    return response.json()
  }
}

场景3:平台特定样式处理

import { isWeapp, isH5 } from '@/utils/platform'

const getPlatformStyles = () => {
  const baseStyles = 'p-4 rounded-lg'
  
  if (isWeapp()) {
    return `${baseStyles} bg-green-100 text-green-800`
  }
  
  if (isH5()) {
    return `${baseStyles} bg-blue-100 text-blue-800 shadow-lg`
  }
  
  return baseStyles
}

与 Taro API 的集成

平台检测工具与 Taro 的 API 完美集成,可以结合使用:

import { isWeapp, isH5 } from '@/utils/platform'
import Taro from '@tarojs/taro'

// 平台特定的导航
const navigateToPage = (url: string) => {
  if (isWeapp()) {
    Taro.navigateTo({ url })
  } else if (isH5()) {
    window.location.href = url
  }
}

// 平台特定的存储
const setStorage = (key: string, value: any) => {
  if (isWeapp()) {
    Taro.setStorageSync(key, value)
  } else if (isH5()) {
    localStorage.setItem(key, JSON.stringify(value))
  }
}

注意事项

  1. 必须在 Taro 环境中使用:这些工具函数依赖于 Taro 的运行时环境
  2. 服务端渲染:在 SSR 环境中使用时需要添加环境判断
  3. 测试环境:在单元测试时可能需要 mock Taro 环境
  4. 性能优化:工具函数都是轻量级的,不会带来性能开销

扩展建议

可以根据项目需要扩展更多平台检测函数:

```typescript // 在 platform.ts 中添加更多检测函数 export const isAlipay = (): boolean => { return getPlatform() === Taro.ENV_TYPE.ALIPAY }

export const isBaidu = (): boolean => { return getPlatform() === Taro.ENV_TYPE.SWAN }