react-router v4 按需加载的配置方法

Posted SunLemon

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react-router v4 按需加载的配置方法相关的知识,希望对你有一定的参考价值。

在react项目开发中,当访问默认页面时会一次性请求所有的js资源,这会大大影响页面的加载速度和用户体验。所以添加按需加载功能是必要的,以下是配置按需加载的方法:

安装bundle-loader

 npm install --save-dev bundle-loader

定义Bundle.js

import React, { Component } from ‘react‘;
    export default class Bundle extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                // short for "module" but that‘s a keyword in js, so "mod"
                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({
                    // handle both es imports and cjs
                    mod: mod.default ? mod.default : mod
                })
            })
        }

        render() {
            if (!this.state.mod)
                return false
            return this.props.children(this.state.mod)
        }
    }

app.jsx配置

import React from ‘react‘;
    import ReactDOM from ‘react-dom‘;
    import { HashRouter, Route } from ‘react-router-dom‘;
    import * as routePaths from ‘./js/constants/routePaths‘;
    import Bundle from ‘./js/constants/Bundle.js‘;
    //默认打开页面直接引入
    import Index from ‘./js/pages/Index‘;
    //其他页面异步引入
    import CardContainer from ‘bundle-loader?lazy&name=app-[name]!./js/pages/Card‘;
    import ‘./assets/css/index.scss‘;

    const Card = () => (
        <Bundle load={CardContainer}>
            {(Card) => <Card />}
        </Bundle>
    )

    ReactDOM.render((
        <HashRouter>
            <div className="container">
                <Route path={routePaths.INDEX} exact component={Index} />
                <Route path=‘/card‘ component={Card} />
            </div>
        </HashRouter>
        ),
        document.getElementById(‘app‘)
    );

webpack.config.js 修改

 webpackConfig.output = {
        path: path.resolve(__dirname, ‘build/‘ + config.ftpTarget),
        publicPath: config.publicPath + ‘/‘,
        filename: ‘js/[name].js‘,
        chunkFilename: ‘js/[id].js‘
    }

这样就可以实现页面js资源按需加载了,打包后的文件命名可以根据自己需要设置。

react-router v4 中文官网:http://reacttraining.cn/web/guides/quick-start

以上是关于react-router v4 按需加载的配置方法的主要内容,如果未能解决你的问题,请参考以下文章

React引入AntD按需加载报错

Echarts的按需加载

Vuetify按需加载配置

webpack antd 按需加载

react16.8 antd按需加载配置(已经弹出和未弹出分别的配置)

react-route4 按需加载配置心得