我正在寻找一种方法来优化一个纯反应原生移动应用程序的启动时间。
作为一个JavaScript框架,是否可以将JavaScript文件捆绑成单独的文件,比如common.js和app.js。我通过谷歌搜索"react native webpack“之类的关键字,但似乎所有这些库都被弃用或过时了,比如react-native-webpack-server,react-native-webpack-starter-kit等。
我想知道在座的任何人是否也在寻找在react原生中优化JavaScript捆绑包的方法。或者,也许这些第三方捆绑包方法已经被Facebook标准捆绑包克服了?
发布于 2018-07-10 11:14:21
您可以动态加载您的组件,这样您的bundle.js将只包含所需的js的一小部分,而当您导航时,您将请求其他不同的部分/部分。
你可以这样做,而不是用传统的方式:import App from './containers/App/App';:
class ImportedComponent extends Component {
state = {
component: null
}
componentWillMount() {
this.props.load()
.then((mod) => this.setState(() => ({
component: mod.default
})))
}
render() {
return this.props.children(this.state.component)
}
}
const App = (props) => (
<ImportedComponent load={() => import('./containers/App/App')}>
{(Component) => Component === null ? <h6 className="loading-message">Loading...</h6> : <Component {...props}/>}
</ImportedComponent>
)或者你可以延迟加载你的组件本身。例如,假设我有Moment JS,并且我不想在需要它之前加载它。所以我能做的是:
1)创建状态并设置为null。
constructor(props){
super(props);
this.state = {
lazyLoadedComponent: () => null
}
}2)使用带有等待的异步componentDidMount,尝试捕获并更新componentDidMount上的状态lazyLoadedComponent
async componentDidMount(){
try {
const Moment = await import('react-moment');
this.setState({ lazyLoadedComponent: (data)=>{
return React.createElement(Moment.default, {format:'MM/DD/YY'}, data)
}
});
}
catch(err) {
this.setState({ lazyLoadedComponent: <div>{`Failed to load component: ${err}`}</div> });
}
}3)在render上调用组件:
{this.state.lazyLoadedComponent(value.createdOn)}通过遵循这两个示例,您应该看到的是250KB以下的bundle.js。
发布于 2019-10-11 18:52:44
作为一种可能的解决方案,您可以使用metro捆绑器提供的ram-bundle格式。
在这种情况下,您将不会加载整个js-bundle -您将只加载在启动时需要的部分(在许多应用程序中有很多地方,用户甚至可能看不到,并且此功能允许您加载这些部分,仅当它们需要时)。因此您可以简化入口点,只加载捆绑包中的一小部分。
你可以看看react-native-bundle-splitter。这个库与几乎所有流行的导航库很好地集成在一起,并允许您推迟加载特定的路线。例如,如果您有一个登录屏幕,则只能在启动时加载此屏幕,所有其他屏幕在后台加载或开始加载,只有当用户可以看到它们时。
https://stackoverflow.com/questions/44630292
复制相似问题