webpack v3 结合 react-router v4 做 dynamic import — 按需加
为什么要做dynamic import?dynamic import不知道为什么有很多叫法,什么按需加载,懒加载,Code Splitting,代码分页等。 为什么选择 webpack 3?
完整的 react spa 项目地址GitHub项目地址 这个一个完整的项目,这节相关的内容可在router/routerMap.jsx中找到。 第一步:安装 babel-plugin-syntax-dynamic-importbabel用的是babel-env,使用方法可以去babel官方学习,实践可看我项目的源代码。
第二步:安装 react-loadable
第三步: 编辑routerMapimport React from 'react'; import { HashRouter as Router,Route,Switch } from 'react-router-dom'; import createHistory from 'history/createBrowserHistory'; const history = createHistory(); import App from 'containers'; // 按路由拆分代码 import Loadable from 'react-loadable'; const MyLoadingComponent = ({ isLoading,error }) => { // Handle the loading state if (isLoading) { return <div>Loading...</div>; } // Handle the error state else if (error) { return <div>Sorry,there was a problem loading the page.</div>; } else { return null; } }; const AsyncHome = Loadable({ loader: () => import('../containers/Home'),loading: MyLoadingComponent }); const AsyncCity = Loadable({ loader: () => import('../containers/City'),loading: MyLoadingComponent }); const AsyncDetail = Loadable({ loader: () => import('../containers/Detail'),loading: MyLoadingComponent }); const AsyncSearch = Loadable({ loader: () => import('../containers/Search'),loading: MyLoadingComponent }); const AsyncUser = Loadable({ loader: () => import('../containers/User'),loading: MyLoadingComponent }); const AsyncNotFound = Loadable({ loader: () => import('../containers/404'),loading: MyLoadingComponent }); // 路由配置 class RouteMap extends React.Component { render() { return ( <Router history={history}> <App> <Switch> <Route path="/" exact component={AsyncHome} /> <Route path="/city" component={AsyncCity} /> <Route path="/search/:category/:keywords?" component={AsyncSearch} /> <Route path="/detail/:id" component={AsyncDetail} /> <Route path="/user" component={AsyncUser} /> <Route path="/empty" component={null} key="empty" /> <Route component={AsyncNotFound} /> </Switch> </App> </Router> ); // 说明 // empty Route // https://github.com/ReactTraining/react-router/issues/1982 解决人:PFight // 解决react-router v4改变查询参数并不会刷新或者说重载组件的问题 } } export default RouteMap; 大功告成我们可以运行webpack,然后就能看到效果(图仅为dev环境,build才会再打包一个vendor.js,为什么要有vendor.js,请见devDependencies和dependencies的区别 >>)
参考文章Code Splitting in Create React App Q&A有同学表示,我的方法做页面分离并没有什么好处,因为每个页面都依赖了三方库的代码,所以其实页面有很多冗余代码,能想到这点很棒,已经开始有架构思维了。不过,注意这个想法在 那到了 看完以后,我们就可以知道,为什么我之前说“注意这个想法在 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |