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