我有一个要导出许多文件的项目。现在,我使用CommonJS延迟导出这些文件:
module.exports = {
get AccessibilityInfo() {
return require('../Components/AccessibilityInfo/AccessibilityInfo');
},
get ActivityIndicator() {
return require('../Components/ActivityIndicator/ActivityIndicator');
},
// .... many other files
}
ReactNative做同样的事情React Native,这样,仅在特定导入文件时才加载文件。
我想使用ESModule重构此文件,但是我找不到延迟导出文件的方法。有没有办法用ESModule延迟导出文件?是否有必要使用ESModule延迟导出文件?
ECMAScript执行此操作的方法是通过动态import()
。语法基本相同,除了可以returns a promise(它很棒-表示该操作不会锁定线程)外,它的功能与您期望的相同。您的代码可以例如看起来像这样:
export const getAccessibilityInfo = () =>
import("../Components/AccessibilityInfo/AccessibilityInfo");
export const getActivityIndicator = () =>
import("../Components/ActivityIndicator/ActivityIndicator");
然后您将像这样抓取这些模块:
import { getActivityIndicator } from "./the/module/above";
const ActivityIndicatorPromise = getActivityIndicator();
// Whenever you need to use the ActivityIdicator module, you first need to await for the promise resolution
ActivityIndicatorPromise.then(ActivityIndicatorModule => {
// Do what you want here...
});
您可以在此处了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports。它还列出了首选该语法的情况。如果您希望使用静态导入语法(import X from '../whatever';
)可以做到这一点,请放心-不可能。
No,无法在本机反应中延迟输出
导出对性能没有影响
导入/需要文件必须包含在JS Bundle中]
内存中存在的组件会影响性能
解决方案1:动态导入
但是您只能像这样动态加载组件
const allPaths = { path1: require('file path1').default, path2: require('file path2').default };
const MyComponent = allPaths('path1')
在此情况下,仅path1组件将处于活动状态的allpaths('path1')
_
解决方案2:停止渲染其他组件树
在特定条件下停止渲染,因此其他树不应在内存中处于活动状态,并且不会对性能产生任何影响
render() {
const {isReady} = this.state;
if(!isReady)
{
return null;
}
return (
<ActualComponent />
)
}