跟着react项目的迭代开辟,会发明build 下静态文件包的体积会愈来愈痴肥,初次阅读网页,白屏或loading时刻愈来愈长,所以代码拆分异常必要:
一、 react-loadable 组件拆分:
装置:
npm install react-loadable -S;
运用要领: App组件中导入 react-loadable组件,app.js 中引入一下代码
:
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/>;
}
}
Loading 组件内容:
import React from "react"
export default () => {
return <div style={{ position: "fixed", left: "50%", top: "50%"}}>Loading......</div>
}
二、异步函数拆分
建立异步组件:
在src目录下建立异步组件 AsyncComponent
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 Com = this.state.component;
return (Com ? <Com {...this.props} /> : null)
}
}
return AsyncComponent;
}
运用异步组件
我们将运用它asyncComponent来动态导入我们想要的组件。
const Home = asyncComponent(() => import(“./components/Home”));
而不是静态导入我们的组件。
import Home from “./components/Home”;
实例:
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’;
import asyncComponent from “./AsyncComponent”
const Abc= asyncComponent(() => import(“./Abc”));
const Bac = asyncComponent(() => import(“./Bac”));
class App extends Component {
static state = {
}
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;
三、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’);
});