[英]Conditional imports in React Native
我在讓條件導入在 React Native 中工作時遇到了一些麻煩。
我有一些在 React Web 應用程序和 React Native 中使用的文件。
我想要什么:
if(process.env.REACT_PLATFORM === 'WEB') {
import('some_file').then(({someFunc})=> someFunc())
}
因為 'some_file' 導入react_router
。
然而,這個導入仍在發生,RN 地鐵打包器拋出
UnableToResolveError: Unable to resolve module 'react-router' from 'some_file'.
即使我將其替換為:
if(false) {
import('some_file').then(({someFunc})=> someFunc())
}
它仍然嘗試加載some_file
。 如果滿足條件,是否只導入/需要此文件?
干杯!
編輯:我嘗試過的事情:
經過一番搜索,結果發現動態導入可能有點痛苦。
這是我想出的解決方案,我已經在 node.js 中嘗試過了。
const MODULE_NAME = <CONDITION> ? require(MODULE_A) : require(MODULE_B);
或者,我想你可以做這樣的事情;
const MODULE_TO_IMPORT = 'MODULE_IMPORT_STRING';
const MODULE_NAME = import(MODULE_TO_IMPORT).then(({someFunc}) => someFunc());
但問題是這些都需要以任何方式導入模塊。
您可以將導入放置在具有native.js
擴展名的組件中,並且它只會綁定到移動設備 (ios/android)。 例如 MyComponent.native.js 然后你有一個同名但擴展名為.js
web 組件。 例如我的 Component.js
當您從 './components/MyComponent' 導入 MyComponent 時,正確的一個將被導入而另一個被忽略。
對於 React-navive-web,我們可以使用特定於平台的管理代碼,這些代碼將在移動應用程序和 Web 中進行管理。
特定於 Web 的代碼 # 較小的平台差異可以使用 Platform 模塊。
import { Platform } from 'react-native';
const styles = StyleSheet.create({
height: (Platform.OS === 'web') ? 200 : 100,
});
例如,在您的項目中有以下文件:
MyComponent.android.js
MyComponent.ios.js
MyComponent.web.js
And the following import:
從 './MyComponent' 導入 MyComponent; React Native 將自動為每個特定的目標平台導入正確的變體。
特定於平台的導入很好,但在網絡上對您沒有幫助。
package.json
react-native
部分是您的朋友:
"react-native": {
"module1": false,
"module2": "module3"
}
有了這個設置
// module1
export const x = 1
// module2
export const x = 2
// module3
export const x = 3
// will result in
import {x} from 'module1'
console.log( x === undefined ) // in the react-native environment
console.log( x === 1 ) // in the browser
import {x} from 'module2'
console.log( x === 3 ) // in the react-native environment
console.log( x === 2 ) // in the browser
import {x} from 'module3'
console.log( x === 3 ) // in the react-native environment
console.log( x === 3 ) // in the browser
文檔可以在這里找到。 它用於browser
部分,但react-native
部分的工作方式相同。
我遇到了一個問題,我正在處理的項目使用react-native-tvos
,我嘗試添加react-native-ad-manager
作為依賴項,但它不支持 tvOS,所以我想動態導入廣告管理器非 tvOS 平台的依賴。 我能夠讓它像這樣工作:
import {Platform} from 'react-native';
const NullComponent = (props: any) => null;
const AdComponent = () => {
const [Banner, setBanner] = React.useState(() => NullComponent);
if (!Platform.isTV) {
import('react-native-ad-manager')
.then(({Banner: AdBanner}) => {
setBanner(() => AdBanner);
})
}
return (
<Banner />
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.