Webpack懶加載React Router的頁面組件

在瀏覽器打開React單頁應(yīng)用,習(xí)慣上會把整個應(yīng)用所有的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'

看到?jīng)]有,就是用一個叫做lazy()的方法,去包住原來的那個React自定義組件名,如Home, About等。

四、正常運行你的webpack的編譯過程,你會發(fā)現(xiàn)原來所生成的單一的JS文件,如bundle.js,現(xiàn)在已經(jīng)變成了像下面這樣的四個文件。

bundle.js
bundle-0.js
bundle-1.js
bundle-2.js
bundle-3.js

五、快去打開瀏覽器看看,是不是真的實現(xiàn)了JS懶加載。

如打開http://localhost:7000/about,會加載bundle.js和bundle-3.js

image.png

如打開http://localhost:7000/case,會加載bundle.js和bundle-1.js

image.png

(本文供刁導(dǎo)參考)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容