Javascript 动态路由代码拆分检查模块是否已加载
我认为代码拆分的问题在于,如果模块很大,用户第一次看到的是一个空白屏幕和延迟Javascript 动态路由代码拆分检查模块是否已加载,javascript,reactjs,webpack,ecmascript-6,webpack-2,Javascript,Reactjs,Webpack,Ecmascript 6,Webpack 2,我认为代码拆分的问题在于,如果模块很大,用户第一次看到的是一个空白屏幕和延迟 function errorLoading(err) { console.error('Dynamic page loading failed', err); } function loadRoute(cb) { return (module) => cb(null, module.default); // I can't find any flag here
function errorLoading(err) {
console.error('Dynamic page loading failed', err);
}
function loadRoute(cb) {
return (module) => cb(null, module.default); // I can't find any flag here
}
const routes = {
component: App,
childRoutes: [
{
path: '/',
getComponent(location, cb) {
System.import('pages/Home')
.then(loadRoute(cb))
.catch(errorLoading);
}
}
]
};
export default () => <Router history={browserHistory} routes={routes} />;
函数错误加载(err){
控制台错误('动态页面加载失败',错误);
}
功能加载路径(cb){
return(module)=>cb(null,module.default);//我在这里找不到任何标志
}
常数路由={
组件:应用程序,
儿童路线:[
{
路径:“/”,
getComponent(位置,cb){
系统导入(“页面/主页”)
.然后(装载路线(cb))
.捕获(错误加载);
}
}
]
};
导出默认值()=>;
下面是一个使用基于动态路由的代码拆分的工作示例
如何检查模块是否已加载?我必须放置一个加载指示器。要使此工作正常,您需要在组件代码中动态加载捆绑包,而不是
getComponent
hook
在我的应用程序中,有一个名为LazyComponent
的组件,可以在需要时动态加载捆绑包。此外,它还允许您在加载大型捆绑包时显示某些内容:
class LazyComponent extends React.Component {
constructor() {
this.state = {Component: null};
super();
}
componentDidMount() {
const pageName = this.props.location.params.page;
System.import(`pages/${pageName}.js`).then(
Component => this.setState({Component}),
error => this.setState({error})
)
}
render() {
const { Component, error } = this.state;
// render error message when bundle has failed to load
if(error) {
return <div>{error.message}</dib>
}
// render loader while component is not ready
if(!Component) {
return <div>Loading...</div>
}
// render the component itself
return <Component {...this.props} />
}
}
一般来说,我的建议不是“检查是否加载”,而是“如果在X毫秒内没有渲染,请显示微调器。这对你有用吗?@loganfsmyth没有标志来检查,这是我的问题。你的建议是使用setinterval来检查?哇,真让人吃惊!不知道我可以在另一个组件中使用系统导入。但是这种方法有什么限制吗?我在最近2个月的应用程序中一直在使用它,我目前正在开发。到目前为止还没有任何限制
const routes = {
component: App,
childRoutes: [
{
path: '/',
component: LazyComponent
}
]
};