Webpack懒加载React Router的页面组件

在浏览器打开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

clipboard.png

如打开http://localhost:7000/case,会加载bundle.js和bundle-1.js

clipboard.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值