码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-05-25 19:17:52      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:word   体验   def   页面   .config   中文   filename   请求   com   

在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 按需加载的配置方法

标签:word   体验   def   页面   .config   中文   filename   请求   com   

原文地址:https://www.cnblogs.com/sunLemon/p/9090031.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!