【翻譯】基于 Create React App路由4.0的異步組件加載(Code Splitting)
基于 Create React App路由4.0的異步組件加載
本文章是一個(gè)額外的篇章,它可以在你的React app中,幫助加快初始的加載組件時(shí)間。當(dāng)然這個(gè)操作不是完全必要的,但如果你好奇的話,請隨意跟隨這篇文章一起用Create React App和 react路由4.0的異步加載方式來幫助react.js構(gòu)建大型應(yīng)用。
代碼分割(Code Splitting)
當(dāng)我們用react.js寫我們的單頁應(yīng)用程序時(shí)候,這個(gè)應(yīng)用會(huì)變得越來越大,一個(gè)應(yīng)用(或者路由頁面)可能會(huì)引入大量的組件,可是有些組件是***次加載的時(shí)候是不必要的,這些不必要的組件會(huì)浪費(fèi)很多的加載時(shí)間。
你可能會(huì)注意到 Create React App 在打包完畢之后會(huì)生成一個(gè)很大的.js文件,這包含了我們應(yīng)用程序需要的所有JavaScript。但是,如果用戶只是加載登錄頁面去登錄網(wǎng)站,我們加載應(yīng)用程序的其余部分是沒有意義的。在我們的應(yīng)用程序還很小的時(shí)候,這并不是一個(gè)問題,但是它卻是我們程序猿優(yōu)化的一個(gè)東西。為了解決這個(gè)問題,Create React App有一個(gè)非常簡單的代碼分割的的方案。
代碼分割和 react-router
在我們 react app 中,常見的路由配置可能是像下面一樣的
- /* Import the components */
- import Home from './containers/Home';
- import Posts from './containers/Posts';
- import NotFound from './containers/NotFound';
- /* Use components to define routes */
- export default () => (
- <Switch>
- <Route path="/" exact component={Home} />
- <Route path="/posts/:id" exact component={Posts} />
- <Route component={NotFound} />
- </Switch>
- );
我們一開始引入這些組件,然后定義好的路徑,會(huì)根據(jù)我們的路由去匹配這些組件。
但是,我們靜態(tài)地在頂部導(dǎo)入路由中的所有組件。這意味著,不管哪個(gè)路由匹配,所有這些組件都被加載。我們只想加載對匹配路由的時(shí)候才加載響應(yīng)的組件。下面我們一步步來完成這個(gè)使命。
創(chuàng)建一個(gè)異步組件
創(chuàng)建一個(gè)js 文件,如: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;
- }
我們在這里做了一些事情:
- 這個(gè)asyncComponent 函數(shù)接受一個(gè)importComponent 的參數(shù),importComponent 調(diào)用時(shí)候?qū)?dòng)態(tài)引入給定的組件。
- 在componentDidMount 我們只是簡單地調(diào)用importComponent 函數(shù),并將動(dòng)態(tài)加載的組件保存在狀態(tài)中。
- ***,如果完成渲染,我們有條件地提供組件。在這里我們?nèi)绻粚憂ull的話,也可提供一個(gè)菊花圖,代表著組件正在渲染。
使用異步組件
現(xiàn)在讓我們使用我們的異步組件,而不是像開始的靜態(tài)去引入。
- import Home from './containers/Home';
我們要用asyncComponent組件來動(dòng)態(tài)引入我們需要的組件。
tip: 別忘記 先 import asyncComponent from './AsyncComponent
- const AsyncHome = asyncComponent(() => import('./containers/Home'));
我們將要使用 AsyncHome 這個(gè)組件在我們的路由里面
- <Route path="/" exact component={AsyncHome} />
現(xiàn)在讓我們回到Notes項(xiàng)目并應(yīng)用這些更改。
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>
- );
只需幾次更改就相當(dāng)酷了。我們的app都是設(shè)置了代碼分割而的。也沒有增加太多的復(fù)雜性。
這里我們看看之前的這個(gè)src/Routes.js路由文件
- import React from 'react';
- import { Route, Switch } from 'react-router-dom';
- import AppliedRoute from './components/AppliedRoute';
- import AuthenticatedRoute from './components/AuthenticatedRoute';
- import UnauthenticatedRoute from './components/UnauthenticatedRoute';
- import Home from './containers/Home';
- import Login from './containers/Login';
- import Notes from './containers/Notes';
- import Signup from './containers/Signup';
- import NewNote from './containers/NewNote';
- import NotFound from './containers/NotFound';
- export default ({ childProps }) => (
- <Switch>
- <AppliedRoute path="/" exact component={Home} props={childProps} />
- <UnauthenticatedRoute path="/login" exact component={Login} props={childProps} />
- <UnauthenticatedRoute path="/signup" exact component={Signup} props={childProps} />
- <AuthenticatedRoute path="/notes/new" exact component={NewNote} props={childProps} />
- <AuthenticatedRoute path="/notes/:id" exact component={Notes} props={childProps} />
- { /* Finally, catch all unmatched routes */ }
- <Route component={NotFound} />
- </Switch>
- );
注意,不要在頂部的引入所有的組件。我們正在創(chuàng)建這些代碼分割的功能,以便在必要時(shí)為我們進(jìn)行動(dòng)態(tài)導(dǎo)入。
現(xiàn)在你運(yùn)行npm run build 您將看到代碼已經(jīng)被分割成一個(gè)個(gè)小文件。
下面是部署好的在網(wǎng)站的真實(shí)截圖
每個(gè).chunk.js都是需要的時(shí)候才加載的。當(dāng)然我們的程序是相當(dāng)小的,并且分離在各個(gè)部分的小組件,是不需要這樣子按需加載的。還是看你項(xiàng)目的需求。