主题
Taro 常见问题
条件编译
提示: Taro 的平台标识符通常为 weapp(微信)、h5、alipay、rn。
在 "JS/TS" 中
js
if (process.env.TARO_ENV === 'h5') {
console.log('H5平台')
}
if (process.env.TARO_ENV === 'weapp') {
console.log('微信小程序平台')
}在 "JSX" 中
jsx
// React 风格
{
process.env.TARO_ENV === 'h5' && <View>H5标题</View>
}
{
process.env.TARO_ENV === 'weapp' && <View>微信小程序标题</View>
}在 "CSS" 中
less
/* #ifdef h5 */
.title {
color: red;
}
/* #endif */
/* #ifdef weapp */
.title {
color: blue;
}
/* #endif */在 "config" 中
Taro 支持在 app.config.js 或页面配置文件(如 index.config.js)中使用条件编译:
使用逻辑判断:
js// 本质也是 JS/TS 文件 // index.config.js const config = { navigationBarTitleText: '通用标题', } if (process.env.TARO_ENV === 'weapp') { config.navigationBarTitleText = '微信特有标题' } if (process.env.TARO_ENV === 'h5') { config.navigationBarTitleText = 'H5特有标题' } export default config使用不同后缀的文件,例如:
index.config.js(默认配置)index.weapp.config.js(仅微信端生效)index.h5.config.js(仅 H5 端生效)
注意: 这种后缀命名方式同样适用于 .js、.jsx、.scss 等文件。例如,
List.weapp.tsx和List.h5.tsx,Taro 会根据当前编译平台自动引入对应的文件。
请求拦截
js
import Taro from '@tarojs/taro'
const customInterceptor = (chain) => {
const requestParams = chain.requestParams
const { url, method } = requestParams
// 请求前逻辑:比如添加 loading
Taro.showLoading({ title: '加载中...' })
return chain.proceed(requestParams).then((res) => {
// 响应后逻辑
Taro.hideLoading()
if (res.statusCode === 200) {
return res.data // 直接返回数据层
} else {
return Promise.reject(res)
}
})
}
// 注册拦截器
Taro.addInterceptor(customInterceptor)
// 使用时
Taro.request({ url: '/api/user' })开发问题
Taro 框架静态分析
js
import Taro from '@tarojs/taro'
import { showLoading, hideLoading } from '@tarojs/taro'无论你通过 Taro.showLoading 还是直接使用 showLoading,最终打包生成的生产环境代码体积是没有区别的。
在开发中,尽量选择某一种风格进行开发。当然更推荐直接使用 Taro.showLoading 的方式,因为 Taro 的静态分析工具能够更好地识别和优化这些调用。
