Webpack懒加载React Router的页面组件
来源:互联网 发布:用c语言编写爱心 编辑:程序博客网 时间:2024/06/07 23:38
在浏览器打开React单页应用,习惯上会把整个应用所有的JS文件一次性加载完。什么?暂时不需要的JS文件也要加载,这肯定很慢吧?对。那你不妨试试下面这种对JS文件的懒加载,看合不合你项目使用。
一、安装bundle-loader依赖
npm i --save-dev bundle-loader
二、定义一个叫作lazy.js的React高阶类。
import React, {Component} from 'react'import PropTypes from 'prop-types'class Lazy extends Component { constructor (props) { super(props) this.state = { mod: null } } componentWillMount () { this.load(this.props) } componentWillReceiveProps (nextProps) { if (nextProps.load !== this.props.load) { this.load(nextProps) } } load (props) { this.setState({ mod: null }) props.load((mod) => { this.setState({ mod: mod.default ? mod.default : mod }) }) } render () { return this.state.mod ? this.props.children(this.state.mod) : null }}Bundle.propTypes = { load: PropTypes.any, children: PropTypes.any}export default function lazy (lazyClass) { return function Wrapper (props) { return <Bundle load={lazyClass}> {(Clazz) => <Clazz {...props} />} </Bundle> }}
三、对<Router>部分的代码进行修改。
改前:
<Router history={hashHistory}> <div> <Route exact path={['/', '/index.html']} component={Home} /> <Route path='/case' component={Demo} /> <Route path='/about' component={About} /> <Route path='/article' component={Article} /> </div> </Router>
改后:
<Router history={hashHistory}> <div> <Route exact path={['/', '/index.html']} component={lazy(Home)} /> <Route path='/case' component={lazy(Demo)} /> <Route path='/about' component={lazy(About)} /> <Route path='/article' component={lazy(Article)} /> </div> </Router>
使用之前,记得先把lazy.js import进来。如
import lazy from './lazy.js'
看到没有,就是用一个叫做lazy()的方法,去包住原来的那个React自定义组件名,如Home, About等。
四、正常运行你的webpack的编译过程,你会发现原来所生成的单一的JS文件,如bundle.js,现在已经变成了像下面这样的四个文件。
bundle.js
bundle-0.js
bundle-1.js
bundle-2.js
bundle-3.js五、快去打开浏览器看看,是不是真的实现了JS懒加载。
如打开
http://localhost:7000/about
,会加载bundle.js和bundle-3.js如打开http://localhost:7000/case,会加载bundle.js和bundle-1.js
(本文供刁导参考)
作者:一米米尺
链接:http://www.jianshu.com/p/85371fbd1985
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
阅读全文
0 0
- Webpack懒加载React Router的页面组件
- 基于 Webpack 2 的 React Router 懒加载路由配置
- Webpack + react-router 按需加载
- webpack+react-router按需加载入门
- React router+ webpack实现:按需加载
- React-router中,结合webpack实现按需加载
- react +webpack+express router实现登录与页面跳转
- React-Router+antd+webpack+babel的一个详细demo
- React+Webpack+Router搭建React基础工程
- react+redux+router+webpack+immutable.js框架
- webpack-dev-server 支持 react-router BrowserHistory
- react-router 按需加载
- React-Router传参取值页面跳转
- React-Router的动态加载实例与createElement
- React+router+redux兼容ie8下的页面效果
- React Router 页面传值的四种方法
- React Router页面传值的三种方法
- webpack-3 react-router-4 react-15.6 升级记录
- Linux 安装 Oracle11g R2 详细教程
- 行为识别阅读笔记(paper+code):Real-time Action Recognition with Enhanced Motion Vector CNNs
- layer父子页面交互
- 最小二乘法-一元回归初等数学证明
- layer弹窗iframe页面,关闭弹窗方法导致form表单无法提交到服务器
- Webpack懒加载React Router的页面组件
- 看完让你彻底搞懂Websocket原理
- 那些一心想要离开 BAT 的人,后来怎么样了?
- QT4-->QT5的过渡
- 蓝桥杯-未名湖边的烦恼
- 论工程师的职业素养养成
- 匿名函数与立即执行函数
- swift素数
- mysql数据库