1吉捶、antd按需加載
2夺鲜、將開發(fā)環(huán)境改為生產(chǎn)環(huán)境(原build文件31.7M,修改后build文件為4.3M)
將webpack.config.js中的 devtool 設(shè)置為 false
image.png
在使用react-create-app搭建的項(xiàng)目呐舔,在我們編譯打包時(shí)會產(chǎn)生很多.map文件币励,導(dǎo)致編譯后的項(xiàng)目非常大,這個(gè)配置就是讓打包后的文件不包含.map文件
3珊拼、使用動態(tài)路由榄审,需要時(shí)再加載(首屏加載2s,優(yōu)化至1s)
創(chuàng)建一個(gè)component函數(shù) (目的就是為了將router的component實(shí)現(xiàn)異步加載杆麸。)
// 異步按需加載component
function asyncComponent(getComponent) {
return class AsyncComponent extends React.Component {
static Component = null;
state = { Component: AsyncComponent.Component };
componentDidMount() {
if (!this.state.Component) {
getComponent().then(({default: Component}) => {
AsyncComponent.Component = Component
this.setState({ Component })
})
}
}
//組件將被卸載
componentWillUnmount(){
//重寫組件的setState方法搁进,直接返回空
this.setState = (state,callback)=>{
return;
};
}
render() {
const { Component } = this.state
if (Component) {
return <Component {...this.props} />
}
return null
}
}
}
function load(component) {
return import(`${component}`)
}
將已知地址路徑傳遞到一個(gè)函數(shù)并把這個(gè)函數(shù)作為參數(shù)傳遞到 asyncComponent中這樣asyncComponent就能接收到這個(gè)路由的地址了,然后我們要做的就是將這個(gè)asyncComponent函數(shù)帶入到router中昔头。
<Router history={history}>
<Route exact path="/" when="always" component={App}/>
<Route exact path="/detail" component={asyncComponent(() => load('./module/Detail'))}/>
<Route exact path="/detail/processingLog" component={asyncComponent(() => load('./module/earlyWarning/ProcessingLog'))}/>
</Router>
從代碼中可以看出已經(jīng)實(shí)現(xiàn)了router 的component 的引入饼问,這樣自然就可以通過一個(gè)循環(huán)來實(shí)現(xiàn)動態(tài)的加載啦!