RN引用原生库包,不支持浏览器环境解决方案
在开发RN应用中,可能会引用部分仅支持原生环境,但不支持浏览器环境的三方库包;
解决这个问题有两个解决方案
- 引用改
require
方式,通过条件判断,只在原生环境下引用,ps: 此方案通过更改代码结构,不建议这样改,除非逻辑需要 - 代码结构不变,继续通过
import
方式引入,但需要在webpack.config.ts
添加配置,如下
引用位置
import Toast from 'react-native-simple-toast';
...
if (errResponse.message === 'Failed to fetch' || errResponse.message === 'Network request failed') {
// 判断是否在原生环境
Platform.OS !== 'web' ? Toast.showWithGravity('网络错误', Toast.SHORT, Toast.TOP) : $toast.show('网络错误');
} else {
Platform.OS !== 'web' ? Toast.showWithGravity(errResponse.message, Toast.SHORT, Toast.TOP) : $toast.show(errResponse.message);
}
webpack.config.ts
配置
/*
* @Description web环境下额外配置,可以用来替换import库,有些库可能只支持原生,在浏览器环境下会报错
*/
const createExpoWebpackConfigAsync = require('@expo/webpack-config');
// eslint-disable-next-line func-names
module.exports = async function (env, argv) {
const config = await createExpoWebpackConfigAsync(env, argv);
// resolve victory-native as victory for the Web app
config.resolve.alias['victory-native'] = 'victory';
// 在浏览器环境下加载@sentry/react-native
config.resolve.alias['@sentry/react-native'] = '@sentry/browser';
// 在浏览器环境下不加载RNSimpleToast, fix: 在浏览器下因原生组件无法调试问题
config.resolve.alias['react-native-simple-toast'] = 'react-native-toast-notifications';
// Use babel specifically on victory-native files
config.module.rules.push({
test: /.*victory-native\/.*\.js/,
use: {
loader: 'babel-loader',
},
});
return config;
};