隨着react項目的迭代開發,會發現build 下靜態文件包的體積會愈來愈臃腫,首次瀏覽網頁,白屏或loading時間愈來愈長,因此代碼拆分很是必要:css
安裝: npm install react-loadable -S;
:react
import Loadable from 'react-loadable'; import Loading from './my-loading-component'; const LoadableComponent = Loadable({ loader: () => import('./my-component'), loading: Loading, }); export default class App extends React.Component { render() { return <LoadableComponent/>; } }
import React from "react" export default () => { return <div style={{ position: "fixed", left: "50%", top: "50%"}}>Loading......</div> }
建立異步組件:
在src目錄下建立異步組件 AsyncComponentwebpack
import React, { Component } from 'react';
export default function asyncComponent(importComponent) {web
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 Com = this.state.component; return (Com ? <Com {...this.props} /> : null) } } return AsyncComponent;
}npm
咱們將使用它asyncComponent來動態導入咱們想要的組件。redux
const Home = asyncComponent(() => import("./components/Home"));
而不是靜態導入咱們的組件。數組
實例:react-router
import React, { Component } from 'react';
import './App.css';
import { Provider } from 'react-redux'
import store from "./store"
import { HashRouter as Router, Switch, Route } from "react-router-dom"
import Home from "./Home"
import { AppContainer } from 'react-hot-loader';app
import asyncComponent from "./AsyncComponent"
const Abc= asyncComponent(() => import("./Abc"));
const Bac = asyncComponent(() => import("./Bac"));
class App extends Component {
static state = {dom
}
static submint = () => {
}
render() {
return ( <AppContainer> <Provider store={store}> <Router> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/home/aa" component={Abc} /> <Route exact path="/home/bb" component={Bac} /> </Switch> </Router> </Provider> </AppContainer> );
}
}
export default App;
3、require.ensure() 方法
在webpack 2的官網上寫了這麼一句話:
require.ensure() is specific to webpack and superseded by import().
因此,在webpack 2裏面應該是不建議使用require.ensure()這個方法的。可是目前該方法仍然有效,因此能夠簡單介紹一下。包括在webpack 1中也是可使用。下面是require.ensure()的語法:
require.ensure(dependencies: String[], callback: function(require), errorCallback: function(error), chunkName: String)
require.ensure()接受三個參數:
第一個參數dependencies是一個數組,表明了當前require進來的模塊的一些依賴;
第二個參數callback就是一個回調函數。其中須要注意的是,這個回調函數有一個參數require,經過這個require就能夠在回調函數內動態引入其餘模塊。值得注意的是,雖然這個require是回調函數的參數,理論上能夠換其餘名稱,可是其實是不能換的,不然webpack就沒法靜態分析的時候處理它;
第三個參數errorCallback比較好理解,就是處理error的回調;
第四個參數chunkName則是指定打包的chunk名稱。
所以,require.ensure()具體的用法以下:
require.ensure([], require => {let chat = require('/components/chart');someOperate(chat);}, error => {console.log('failed');}, 'mychat');});