taro+react+ts+tailwind微信小程序兼容h5API、组件兼容问题

1.样式兼容

微信小程序所有页面都在page下面,但是taro转成h5后会都嵌套在<taro-view-core>标签内,所以在设置全局样式的时候需要注意

page {
  background: #F3F5F7;
  height: 100%;
}

taro-view-core {
  box-sizing: border-box;
}

2.打开文件方法兼容

由于Taro.openDocument方法不支持h5所以这里需要做环境判断来实现打开文件的方法,在h5中我们可以使用window.open(url, '_blank')来直接打开文件

if (Taro.getEnv() === 'WEAPP') {
      Taro.downloadFile({
        url,
        success: (res) => {
          const filePath = res.tempFilePath
          Taro.openDocument({
            fileType: 'pdf',
            showMenu: true,
            filePath
          })
        }
      })
    } else {
      window.open(url, '_blank')
    }

3.上传文件方法兼容

1.用Taro.chooseMedia()方法实现拍摄或从手机相册中选择图片或视频,这个h5和小程序Taro都兼容,但是Taro.uploadFile()只能在小程序中或者是在对应公众号文章中嵌套的h5页面才能使用,所以在h5中我们可以将本地临时文件路径转成bold格式,然后直接传调后端服务器接口就好

// 首先拿到本地文件路径
const { tempFiles } = await Taro.chooseMedia({
      count,
      mediaType: [`${mediaType}`],
      sourceType: ['album', 'camera'],
      maxDuration: maxFileSize || 60,
      camera: 'back'
    })
// 根据环境判断,小程序和h5分别处理图片给上传图片接口
const handleApiUpload = async (filePath: string) => {
  const token = Taro.getStorageSync('userInfo').token
  let result
  if (process.env.TARO_ENV === 'weapp') {
    const res = await Taro.uploadFile({
      url: `${process.env.TARO_APP_API}opservcenter/opsc/obsFile/uploadFile`,
      filePath,
      name: 'file',
      header: { contentType: 'multipart/form-data', token },
      formData: {} // 这里传服务器需要的数据
    })
    result = JSON.parse(res.data) as Com.ResponseData
  } else {
    const data = await fetch(filePath)
    const file = await data.blob()
    result = await Promise.resolve({
      file
    })
  }
  return result
}

4.tailwindCss样式兼容

由于微信小程序的单位是rpx,h5是px所以在配置默认间距比例时需要根据环境做处理

postcss.config.js文件中处理

const isH5 = process.env.TARO_ENV === 'h5'
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
    'postcss-rem-to-responsive-pixel': {
      viewportWidth: 390,
      // 32 意味着 1rem = 32rpx
      rootValue: isH5 ? 16 : 32,
      // 默认所有属性都转化
      propList: ['*'],
      // 转化的单位,可以变成 px / rpx
      transformUnit: isH5 ? 'px' : 'rpx'
    }
  }
}

5.h5配置

具体可以参考Taro编译配置文档

Taro 文档

config/index.ts文件中添加h5配置

h5: {
      publicPath: '/',
      staticDirectory: 'static',
      output: {
        filename: 'js/[name].[hash:8].js',
        chunkFilename: 'js/[name].[chunkhash:8].js'
      },
      miniCssExtractPluginOption: {
        ignoreOrder: true,
        filename: 'css/[name].[hash].css',
        chunkFilename: 'css/[name].[chunkhash].css'
      },
      postcss: {
        pxtransform: {
          enable: true,
          config: {
            designWidth: 390, // 设计稿宽度
            onePxTransform: true, // 是否转换 1px
            unitPrecision: 5, // 单位转换精度
            propList: ['*'], // 需要转换的属性
            selectorBlackList: [], // 忽略的类名
            replace: true, // 是否直接替换样式
            mediaQuery: false, // 是否转换媒体查询中的单位
            minPixelValue: 0 // 最小转换像素值
          }
        },
        autoprefixer: {
          enable: true,
          config: {}
        },
        cssModules: {
          enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
          config: {
            namingPattern: 'module', // 转换模式,取值为 global/module
            generateScopedName: '[name]__[local]___[hash:base64:5]'
          }
        }
      },
      router: {
        mode: 'browser', // 或者是 'browser'
        customRoutes: {
          // 自定义路由规则
          '/user/authorize': '/pages/authorize/index'
        }
      },
      webpackChain(chain) {
        chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin)
      }
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值