react-router的3种按需加载介绍

react-router的3种按需加载介绍:https://blog.csdn.net/jackTesla/article/details/80792110

react-router的按需加载(推荐第三种)

第一种:

利用react-loadable这个高级组件,要做到实现按需加载这一点,我们将使用的WebPack,babel-plugin-syntax-dynamic-import和react-loadable。

webpack内置了对动态导入的支持; 但是,如果使用Babel(将JSX编译为JavaScript),那么将需要使用babel-plugin-syntax-dynamic-import插件。这是一个仅用于语法的插件,这意味着Babel不会做任何额外的转换。该插件只是允许Babel解析动态导入,因此webpack可以将它们捆绑为代码分割。

.babelrc:

{

“ presets ”:[

“ react ”

],“ plugins ”:[

“ syntax-dynamic-import ”

]

}

react-loadable是用于通过动态导入加载组件的高阶组件。

import Loadable from ‘react-loadable‘;

import Loading from ‘./Loading‘;

const LoadableComponent = Loadable({

loader: () => import(‘./Dashboard‘),

loading: Loading,

})

export default class LoadableDashboard extends React.Component {

render() {

return <LoadableComponent />;

}

}

https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/guides/code-splitting.md

第二种:
    在router3中的按需加载方式

route3中实现按需加载只需要按照下面代码的方式实现就可以了。

const about = (location, cb) => {

require.ensure([], require => {

cb(null, require(‘../Component/about‘).default)

},‘about‘)

}

//配置route

<Route path="helpCenter" getComponent={about} />

在router4以前,我们是使用getComponent的的方式来实现按需加载,getComponent是异步的,只有在路由匹配时才会调用,router4中,getComponent方法已经被移除,所以这种方法在router4中不能使用。

第三种:

create-react-app文档给的react-router按需加载实现:

本人在自己利用webpack+dva+antd+…的多页应用项目中使用的这个方法,相对简单好用。但是有人指出性能上不如Bundle组件(在react-router 4官网上的一个代码拆分的例子),那个人好像还是Create-react-app的主要贡献者。

第一步:创建一个异步组件

创建文件src/components/AsyncComponent.js

import React, { Component } from "react";

export default function asyncComponent(importComponent) {

class AsyncComponent extends Component {

constructor(props) {

super(props);

this.state = {

component: null

};

}

async componentDidMount() {

const { default: component } = await importComponent();

this.setState({

component: component

});

}

render() {

const C = this.state.component;

return C ? <C {...this.props} /> : null;

}

}

return AsyncComponent;

}

第二步:使用异步组件:我们将使用asyncComponent动态导入我们想要的组件。

const AsyncHome = asyncComponent(() => import("./containers/Home"));

src/Routes.js:

import React from "react";

import { Route, Switch } from "react-router-dom";

import asyncComponent from "./components/AsyncComponent";

import AppliedRoute from "./components/AppliedRoute";

import AuthenticatedRoute from "./components/AuthenticatedRoute";

import UnauthenticatedRoute from "./components/UnauthenticatedRoute";

const AsyncHome = asyncComponent(() => import("./containers/Home"));

const AsyncLogin = asyncComponent(() => import("./containers/Login"));

const AsyncNotes = asyncComponent(() => import("./containers/Notes"));

const AsyncSignup = asyncComponent(() => import("./containers/Signup"));

const AsyncNewNote = asyncComponent(() => import("./containers/NewNote"));

const AsyncNotFound = asyncComponent(() => import("./containers/NotFound"));

export default ({ childProps }) =>

<Switch>

<AppliedRoute

path="/"

exact

component={AsyncHome}

props={childProps}

/>

<UnauthenticatedRoute

path="/login"

exact

component={AsyncLogin}

props={childProps}

/>

<UnauthenticatedRoute

path="/signup"

exact

component={AsyncSignup}

props={childProps}

/>

<AuthenticatedRoute

path="/notes/new"

exact

component={AsyncNewNote}

props={childProps}

/>

<AuthenticatedRoute

path="/notes/:id"

exact

component={AsyncNotes}

props={childProps}

/>

{/* Finally, catch all unmatched routes */}

<Route component={AsyncNotFound} />

</Switch>

;

这样就可以了,已经做好代码分片的处理了,你可以npm run build 在build目录下看到一些.chunk.js的文件,就是咱们import()的不同动态调用。

最后在开发者工具中打开network验证.chunk.js的加载效果
————————————————
版权声明:本文为CSDN博主「jackTesla」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/jackTesla/article/details/80792110

原文地址:https://www.cnblogs.com/bydzhangxiaowei/p/12238776.html

时间: 2024-08-02 21:25:11

react-router的3种按需加载介绍的相关文章

react 中使用import()实现按需加载报错 解决方法 --‘import’ and ‘export’ may only appear at the top level

因为项目需要搞一下按需加载,使用import实现代码打包分片按需加载,但是在实际使用中报语法错误.报错信息如下 SyntaxError: 'import' and 'export' may only appear at the top level 啊咧?报错了. 查找发现很多人碰到过,解决方法不同,但是我这个报错适用下边这个方法. npm install --save-dev babel-plugin-syntax-dynamic-import 然后调整babel-loader配置如下: use

利用 React/Redux/React-Router 4/webpack 开发大型 web 项目时如何按需加载

如何设计一个大型 web 项目? React + webpack 如何按需加载? React + React-Router 4 + webpack 如何按需加载? React + Redux + React-Router 4 + webpack 如何按需加载? 实录提要: bundle-loader 和 Webpack 内置的 import() 有什么区别? 按需加载能否支持通过请求后台数据,动态配置页面的的应用场景? 参与过几个 React 项目,被依赖包搞的晕晕的,不知道该怎么选择? 什么包

React Router 按需加载+服务器渲染的闪屏问题

伴随着React协议的『妥协』(v16采用MIT),React为项目的主体,这个在短期内是不会改变的了,在平时使用过程中发现了如下这个问题: 在服务器渲染的时候,刷新页面会出现闪屏的现象(白屏一闪而过) 作为努力最求极致的我,是不能容忍的,而这一现象是半道出现的,也就是在添加按需加载之后.要说清楚这个问题,得从React的服务器渲染开始说起,(急于寻求问题解决方案的,可以直接去文章后半部分) 服务器渲染(SSR)基础原理 React的虚拟DOM是其可被用于服务端渲染的关键.其原理简单的来说就是首

React 按需加载 - 代码分隔

代码分隔 我们现在大多数React项目都是以Webpack 或者 Browserify等将一堆的jsx文件组织一起,并且由一个类似index.js的入口文件串联起来的单页面web页面. 例如: // math.js export function add(a, b) { return a + b; } App: // app.js import { add } from './math.js'; console.log(add(16, 26)); // 42 打完包后: function add

vue router按需加载

1 import Vue from 'vue' 2 import Router from 'vue-router' 3 4 Vue.use(Router); 5 //按需加载,当渲染其他页面时才加载其组件,并缓存,减少首屏加载时间 6 const Index = resolve => require(['@/views/Index.vue'], resolve) 7 const Category = resolve => require(['@/views/Category.vue'], re

react中执行yarn eject配置antd-mobile的按需加载

在使用react做项目时如果用antd-mobile,如果使用按需加载,则需要修改它的配置文件 如果我们不操作yarn eject,则直接操作下面的步骤即可: 在 create-react-app 搭建脚手架时 cnpm install -g create-react-app create-react-app reactDemo cd reactDemo cnpm start 引入 antd-mobile 因为配置文件隐藏了,从而我们需要引入 react-app-rewired 并修改 pack

React引入AntD按需加载报错

背景:React使用create-react-app脚手架创建,然后yarn run eject暴露了配置之后修改less配置, 需求:实现antd组件按需加载与修改主题. 一开始是按照webpack.config.dev.js文件中的配置进行less的配置. 可以看到脚手架创建的config文件为加载loader写了一个公共方法,不是以前的webpack配置,所以仿照他的方式进行配置less文件. 直接复制css的配置,修改成less的配置,然后yarn start重启项目. 此时可以加载le

react+mobx+antd按需加载 出现Support for the experimental syntax &#39;decorators-legacy&#39; isn&#39;t currently enabled

baidu上面的说法大多是在 项目的package.json 中添加decorators-legacy 因为引入了antd的按需加载 所以只需要在config-overrides.js中添加addDecoratorsLegacy() const { override, fixBabelImports,addDecoratorsLegacy } = require('customize-cra'); module.exports = override( fixBabelImports('impor

react中使用antd按需加载(第一部)

什么是react按需加载?简单来说就是当我们引用antd的时候需要引入全局css样式,这会对性能造成一定的影响,那么使用按需加载以后就不需要引入css全局样式了,直接引入功能模块即可,既然需要设置按需加载就要对webpack文件进行修改,需要我们执行npm run eject命令来展开项目的隐藏文件,如果只是简单的修改,我们可以使用react-app-rewired定义全局变量,react-app-rewired的作用就是在不eject的情况下,覆盖create-react-app的配置.具体如