[转] react-router4 实现按需加载
按需加载的背景
React Router 是一个非常出色的路由解决方案,同时也非常容易上手。但是当网站规模越来越大的时候,首先出现的问题是 Javascript 文件变得巨大,这导致首页渲染的时间让人难以忍受。实际上程序应当只加载当前渲染页所需的 JavaScript,也就是大家说的“代码分拆" — 将所有的代码分拆成多个小包,在用户浏览过程中按需加载。
老的方案
这里所说的老是指使用react-router低于4的版本。
在低版本(小于4)的react-router中直接提供了按需加载的方案,示例如下:
const rootRoute = {
path: '/',
indexRoute: {
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('components/layer/HomePage'))
}, 'HomePage')
},
},
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('components/Main'))
}, 'Main')
},
childRoutes: [
require('./routes/baidu'),
require('./routes/404'),
require('./routes/redirect')
]
}
ReactDOM.render(
(
<Router
history={browserHistory}
routes={rootRoute}
/>
), document.getElementById('app')
);
核心代码是router.getComponent,然而在react-router4中,没有router.getComponent了,这样我们该如何实现按需加载呢?
react-router4的实现方案
根据官网的介绍:
One great feature of the web is that we don’t have to make our visitors download the entire app before they can use it.
You can think of code splitting as incrementally downloading the app. While there are other tools for the job, we’ll use Webpack and the bundle loader in this guide.
我们要借助bundle-loader来实现按需加载。
首先,新建一个bundle.js文件:
import React, { Component } from 'react'
export default class Bundle extends React.Component {
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)
}
}
然后,在入口处使用按需加载:
// ...
// bundle模型用来异步加载组件
import Bundle from './bundle.js';
// 引入单个页面(包括嵌套的子页面)
// 同步引入
import Index from './app/index.js';
// 异步引入
import ListContainer from 'bundle-loader?lazy&name=app-[name]!./app/list.js';
const List = () => (
<Bundle load={ListContainer}>
{(List) => <List />}
</Bundle>
)
// ...
<HashRouter>
<Router basename="/">
<div>
<Route exact path="/" component={Index} />
<Route path="/list" component={List} />
</div>
</Router>
</HashRouter>
// ...
webpack.config.js文件配置
output: {
path: path.resolve(__dirname, './output'),
filename: '[name].[chunkhash:8].bundle.js',
chunkFilename: '[name]-[id].[chunkhash:8].bundle.js',
},
完整代码示例
[转] react-router4 实现按需加载的更多相关文章
- react 实现路由按需加载
import() 方法: async.js 文件内容: import React from 'react'; // import "babel-polyfill"; //compo ...
- React引入AntD按需加载报错
背景:React使用create-react-app脚手架创建,然后yarn run eject暴露了配置之后修改less配置, 需求:实现antd组件按需加载与修改主题. 一开始是按照webpack ...
- react 使用antd 按需加载
使用 react-app-rewired 1. 安装react-app-rewired: 由于新的 react-app-rewired@2.x 版本的关系,你还需要安装 customize-cra. ...
- react antd样式按需加载配置以及与css modules模块化的冲突问题
通过create-react-app脚手架生成一个项目 然后运行npm run eject 把webpack的一些配置从react-scripts模块弹射出来, 方便自己手工增减,暴露出来的配置文件在 ...
- react CRA antd 按需加载配置 lessloader
webpack配置 webpack.config.dev.js, webpack.config.prod同理. 'use strict'; const autoprefixer = require(' ...
- react路由按需加载方法
使用router4之后以前的按需加载方法require.ensure 是不好使了. 所以我们改用react-loadable插件做按需加载. 第一步: yarn add react-loadable ...
- React Router 按需加载+服务器渲染的闪屏问题
伴随着React协议的『妥协』(v16采用MIT),React为项目的主体,这个在短期内是不会改变的了,在平时使用过程中发现了如下这个问题: 在服务器渲染的时候,刷新页面会出现闪屏的现象(白屏一闪而过 ...
- react按需加载(getComponent优美写法),并指定输出模块名称解决缓存(getComponent与chunkFilename)
react配合webpack进行按需加载的方法很简单,Route的component改为getComponent,组件用require.ensure的方式获取,并在webpack中配置chunkFil ...
- 快速搭建react项目骨架(按需加载、redux、axios、项目级目录等等)
一.前言 最近整理了一下项目骨架,顺便自定义了一个脚手架,方便日后使用.我会从头开始,步骤一步步写明白,如果还有不清楚的可以评论区留言.先大致介绍一下这个骨架,我们采用 create-react-ap ...
- Ant Design React按需加载
Ant Design是阿里巴巴为React做出的组件库,有统一的样式及一致的用户体验 官网地址:https://ant.design 1.安装: npm install ant --save 2.引用 ...
随机推荐
- AWT和Swing的关系
1.AWT和Swing都是java中的包. 2.AWT(Abstract Window Toolkit):抽象窗口工具包,早期编写图形界面应用程序的包,AWT是通过调用操作系统的native方法实现的 ...
- logback异步输出日志(生产者消费者模型),并非批量写入日志。
一直对logback异步输出日志误解为异步批量写入日志. 今天看了源代码. 首先logback的异步日志是如何配置的: <!-- 管理端用户行为日志异步输出,异步的log片段必须在同步段后面,否 ...
- java Future模式的使用
一.Future模式的使用. Future模式简述 传统单线程环境下,调用函数是同步的,必须等待程序返回结果后,才可进行其他处理. Futrue模式下,调用方式改为异步. Futrue模式的核心在于: ...
- luogu 1993 小K的农场
差分约束+spfa判负环 dfs判负环 #include<bits/stdc++.h> #define rep(i,x,y) for(register int i=x;i<=y;i+ ...
- UE4联机编译光照
UE4联机编译光照需要SwarmCoordinator以及SwarmAgent,在Engine\Binaries\DotNET目录下. SwarmAgent 我们主要关注Distribution Se ...
- luogu P4342 [IOI1998]Polygon
IOI早期这么多dp? 题目要求断掉环上的一边,我们可以断环为链,开两倍数组 容易想到dp,设\(f_{i,j}\)为区间\([i,j]\)的最大值,然后就是个枚举断点的区间dp 不过可能会有负数出现 ...
- [JXOI2018]游戏 (线性筛,数论)
[JXOI2018]游戏 \(solution:\) 这一道题的原版题面实在太负能量了,所以用了修改版题面. 这道题只要仔细读题,我们就可以将题目的一些基本性质分析出来:首先我们定义:对于某一类都可以 ...
- python - wmi模块学习(windwos硬件信息获取)
获取windows操作系统的硬件信息 #!/usr/bin/env python # -*- coding: utf-8 -*- # http://www.cnblogs.com/liu-ke/ im ...
- SpringBoot集成监控管理
(1).添加starter依赖 <dependency> <groupId>org.springframework.boot</groupId> <artif ...
- SpringBoot修改Servlet相关配置
第一种方式在配置文件中进行修改 server.port=8081 server.servlet.context-path=/springboot server.tomcat.uri-encoding= ...