webpack v3 结合 react-router v4 做 dynamic import — 按需加载(懒加载)
为什么要做dynamic import?
dynamic import不知道为什么有很多叫法,什么按需加载,懒加载,Code Splitting,代码分页等。
总之,就是在SPA,把JS代码分成N个页面份数的文件,不在用户刚进来就全部引入,而是等用户跳转路由的时候,再加载对应的JS文件。
这样做的好处就是加速首屏显示速度,同时也减少了资源的浪费。
为什么选择 webpack 3?
- 更高的性能
- 有scope hosting功能,不再需要rollup来处理代码冗余
- 可与react-router结合,更优雅的做dynamic import
- 最重要的一点是,我正经学webpack的时候3已结出了- -
完整的 react spa 项目地址
这个一个完整的项目,这节相关的内容可在router/routerMap.jsx中找到。
第一步:安装 babel-plugin-syntax-dynamic-import
babel用的是babel-env,使用方法可以去babel官方学习,实践可看我项目的源代码。
npm i -D babel-plugin-syntax-dynamic-import 以后, 在.babelrc文件的plungins中加上"syntax-dynamic-import"。
第二步:安装 react-loadable
npm i -S react-loadable 以后,我们就能愉快得做dynamic import了。
第三步: 编辑routerMap
import 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
有同学表示,我的方法做页面分离并没有什么好处,因为每个页面都依赖了三方库的代码,所以其实页面有很多冗余代码,能想到这点很棒,已经开始有架构思维了。不过,注意这个想法在dev环境下,这个同学是对的。
那到了build环境,或者说到了发布环境,又是怎么样的呢?的确,这篇文章我没有提到,请见我的另一篇文章devDependencies和dependencies的区别。这篇文章主要解释了npm的package.json中devDependencies和dependencies区别是什么。
看完以后,我们就可以知道,为什么我之前说“注意这个想法在dev环境下,这个同学是对的”了。因为,我们npm run build以后,webpack会把三方包打包到vendor.js文件,页面逻辑代码不会牵涉其中,每个页面都会引用vendor.js这个文件,这样的话,就不会出现重复引入冗余代码的情况了。
来源:https://segmentfault.com/a/1190000011128817
webpack v3 结合 react-router v4 做 dynamic import — 按需加载(懒加载)的更多相关文章
- [Web 前端] React Router v4 入坑指南
cp from : https://www.jianshu.com/p/6a45e2dfc9d9 万恶的根源 距离React Router v4 正式发布也已经过去三个月了,这周把一个React的架子 ...
- [React Router v4] Render Multiple Components for the Same Route
React Router v4 allows us to render Routes as components wherever we like in our components. This ca ...
- React Router V4发布
React Router V4 正式版发布,该版本相较于前面三个版本有根本性变化,遵循 Just Component 的 API 设计理念. 本次升级的主要变更有: 声明式 Declarative 可 ...
- [React Router v4] Intercept Route Changes
If a user has entered some input, or the current Route is in a “dirty” state and we want to confirm ...
- [React Router v4] Redirect to Another Page
Overriding a browser's current location without breaking the back button or causing an infinite redi ...
- [React Router v4] Conditionally Render a Route with the Switch Component
We often want to render a Route conditionally within our application. In React Router v4, the Route ...
- [React Router v4] Render Catch-All Routes with the Switch Component
There are many cases where we will need a catch-all route in our web applications. This can include ...
- [React Router v4] Render Nested Routes
With React Router v4 the entire library is built as a series of React components. That means that cr ...
- [React Router v4] Parse Query Parameters
React Router v4 ignores query parameters entirely. That means that it is up to you to parse them so ...
随机推荐
- 小程序-TabBar点击切换
这种页面的布局会经常用到,所以在此做个笔记,之后遇到可以节省很多时间 WXML: <view class='listTitle_tab'> <view class='scr ...
- Codeforces Gym101502 H.Eyad and Math-换底公式
H. Eyad and Math time limit per test 2.0 s memory limit per test 256 MB input standard input outpu ...
- python 当pip不能用的时候可以去找python安装包
初学python,一直pip安装各种包,突然间有一天pip莫名其妙不能用了,除了pip help全部都是没反应 百度好像没人出现过pip挂掉的情况 花了一小时修复pip,卸载啊,路径啊,全部无效 百度 ...
- 前端笔记之Vue(七)Vue-router&axios&Vue插件&Mock.js&cookie|session&加密
一.Vue-router(路由) 1.1路由创建 官网:https://router.vuejs.org/zh/ 用 Vue.js + Vue Router 创建单页应用,是非常简单的.使用 Vue. ...
- 中国正式发放5G牌照 详细对比中美两国5G实力
今天,中国5G商用走进新里程:工信部向中国电信.中国移动.中国联通.中国广电发放5G商用牌照,中国也成为继韩国.美国.瑞士.英国后,第五个正式商用5G的国家. 按照之前的规划,中国原定于2020年开启 ...
- HDU 2460 Network 傻逼Tarjan
Network Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Su ...
- 转载:P2P技术原理及应用(1)
转帖allen303allen的空间 作 者:金海 廖小飞 摘要:对等网络(P2P)有3种主要的组织结构:分布式哈希表(DHT)结构.树形结构.网状结构.P2P技术已 经延伸到几乎所有的网络应用领域, ...
- NLP项目
GitHub NLP项目:自然语言处理项目的相关干货整理 自然语言处理(NLP)是计算机科学,人工智能,语言学关注计算机和人类(自然)语言之间的相互作用的领域.本文作者为自然语言处理NLP初学者整理了 ...
- Ext.Ajax.request批量提交表单
介绍一下批量提交grid中数据的问题 js文件中的提交方法如下: listeners: { click: function btnClick(button) { var win = button.up ...
- xshell配置
字体:DejaVu Sans Mono 或者 Consolas 11号