浅谈React Router动态路由

1、webpack的codesplitting

webpack可以通过require.ensure接口实现按需加载。

require.ensure保证了模块的异步调用,当callback回调中调用了一个模块时,可以实现按需加载。

require.ensure([], function() {
 	callback(null, require('…'));
  	//...
});

 

2、react-router实现按需加载

按需加载的作用:主要可以减少首页请求的文件的大小。

react-router中,可以通过getChildRoutes、getIndexRoute、getComponents三个接口结合webpack的code splitting,通过切换路由实现按需加载。

react-router定义了getChildRoutes、getIndexRoute、getComponents这3个方法,这3个方法是异步的,且只在需要时调用,通过这3个方法定义的路由,称之为“渐进式路由匹配”——react-router在匹配到路由时,只是渐进式地加载该路由所需的组件,这样就能实现按需加载。

eg:

import { rootdir } from '../config';
const getIndexRoute = ({ location }, callback) => {
    require.ensure([], () => {
        callback(null, {
            component: require('./Home'),
        });
    }, 'public/home');
};
const getChildRoutes = ({ location }, callback) => {
    const sliced = location.pathname.slice(rootdir.length);
    if(sliced.indexOf('todos') !== -1) {
        require.ensure([], () => {
            callback(null, require('./todos.routes'));
        }, 'public/todos');
        return;
    }
    callback(null, []);
}
注意:

1、require方法的参数不能使用变量,只能使用字符串,如require('./Home')。

2、如果在路由页面使用了require.ensure这种按需加载路由级组件的方式,则在其他地方(包括本页面)就不要再import了,否则不会打包生成chunk文件。也就是说,需要按需加载的路由级组件必须在路由页面进行加载,任何地方都不能通过import引入按需加载的组件。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章