React Native 中的条件导入 [英] Conditional imports in React Native
问题描述
我在 React Native 中使用条件导入时遇到了一些麻烦.
I'm having a bit of trouble getting conditional imports working in react native.
我有一些在 React Web 应用程序和 React Native 中使用的文件.
I have some files that are used in a react web app and in react native.
我想要什么:
if(process.env.REACT_PLATFORM === 'WEB') {
import('some_file').then(({someFunc})=> someFunc())
}
因为 'some_file' 导入了 react_router
.
Because 'some_file' imports react_router
.
然而,这个导入仍在发生,RN Metro bundler 抛出
However, this import is still happening, and the RN metro bundler throws
UnableToResolveError:无法从some_file"解析模块react-router".
即使我将其替换为:
if(false) {
import('some_file').then(({someFunc})=> someFunc())
}
它仍然尝试加载 some_file
.无论如何,如果满足条件,是否只导入/要求此文件?
It still trys to load some_file
. Is there anyway to only import/require this file if a condition is met?
干杯!
我尝试过的事情:
推荐答案
经过一番搜索,结果发现动态导入可能有点痛苦.
After a bit of searching, in turns out dynamic imports can be a bit of a pain.
这是我想出的解决方案,我已经在 node 中尝试过了.
This is the solution I came up with, I've tried it in node.
const MODULE_NAME = <CONDITION> ? require(MODULE_A) : require(MODULE_B);
或者,我想你可以做这样的事情;
Alternatively, I guess you could do something like this;
const MODULE_TO_IMPORT = 'MODULE_IMPORT_STRING';
const MODULE_NAME = import(MODULE_TO_IMPORT).then(({someFunc}) => someFunc());
但问题是这些需要一个以任何方式导入的模块.
But the problem is that these require a module to be imported either way.
这篇关于React Native 中的条件导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!