Webpack3+React16代碼分割的實(shí)現(xiàn)
項(xiàng)目背景
最近項(xiàng)目里有個webpack版本較老的項(xiàng)目,由于升級和換框架暫時不被leader層接受o(╥﹏╥)o,只能在現(xiàn)有條件進(jìn)行優(yōu)化。
webpack3 + react16
webpack v3配置檢查
很明顯項(xiàng)目的配置是從v1繼承過來的,v1->v3的升級較為簡單,參考官網(wǎng)https://webpack.js.org/migrate/3/即可。
loaders變?yōu)閞ules
不再支持鏈?zhǔn)綄懛ǖ膌oader,json-loader不需要配置
UglifyJsPlugin插件需要自己開啟minimize
分析現(xiàn)有包的問題
使用webpack-bundle-analyzer構(gòu)建包后,如圖
問題非常明顯:
除了zxcvbn這個較大的包被拆出來,代碼就簡單的打包為了vender和app,文件很大。
動態(tài)import拆分vender
分析vender的代碼,某些大包,例如libphonenumber.js,使用場景不是很頻繁,將它拆出來,當(dāng)使用到相關(guān)特性時再請求。
參考react官方代碼分割指南, https://react.docschina.org/docs/code-splitting.html#import
import { PhoneNumberUtil } from 'google-libphonenumber' function usePhoneNumberUtil(){ // 使用PhoneNumberUtil }
修改為動態(tài) import()
方式,then和async/await都支持用來獲取異步數(shù)據(jù)
const LibphonenumberModule = () => import('google-libphonenumber') function usePhoneNumberUtil(){ LibphonenumberModule().then({PhoneNumberUtil} => { // 使用PhoneNumberUtil }) }
當(dāng) Webpack 解析到該語法時,會自動進(jìn)行代碼分割。
修改后的效果:
libphonenumber.js(1.chunk.js)從vender中拆分出來了,并且在項(xiàng)目實(shí)際運(yùn)行中,只有當(dāng)進(jìn)入usePhoneNumberUtil流程時,才會向服務(wù)器請求libphonenumber.js文件。
基于路由的代碼分割
React.lazy
參考react官方代碼分割指南-基于路由的代碼分割,https://react.docschina.org/docs/code-splitting.html#route-based-code-splitting。
拆分前示例:
import React from 'react'; import { Route, Switch } from 'react-router-dom'; const Home = import('./routes/Home'); const About = import('./routes/About'); const App = () => ( <Router> <Suspense fallback={<div>Loading...</div>}> <Switch> <Route exact path="/" component={Home}/> <Route path="/about" component={About}/> </Switch> </Suspense> </Router> );
拆分后示例:
import React, { lazy } from 'react'; import { Route, Switch } from 'react-router-dom'; const Home = lazy(() => import('./routes/Home')); const About = lazy(() => import('./routes/About')); const App = () => ( // 路由配置不變 )
拆分后效果:
app.js按照路由被webpack自動拆分成了不同的文件,當(dāng)切換路由時,才會拉取目標(biāo)路由代碼文件。
命名導(dǎo)出
該段引用自 https://react.docschina.org/docs/code-splitting.html#named-exports 。
React.lazy
目前只支持默認(rèn)導(dǎo)出(default exports)。如果你想被引入的模塊使用命名導(dǎo)出(named exports),你可以創(chuàng)建一個中間模塊,來重新導(dǎo)出為默認(rèn)模塊。這能保證 tree shaking 不會出錯,并且不必引入不需要的組件。
// ManyComponents.js export const MyComponent = /* ... */; export const MyUnusedComponent = /* ... */;
// MyComponent.js export { MyComponent as default } from "./ManyComponents.js";
// MyApp.js import React, { lazy } from 'react'; const MyComponent = lazy(() => import("./MyComponent.js"));
自己實(shí)現(xiàn)AsyncComponent
React.lazy包裹的懶加載路由組件,必須要添加Suspense。如果不想強(qiáng)制使用,或者需要自由擴(kuò)展lazy的實(shí)現(xiàn),可以定義實(shí)現(xiàn)AsyncComponent,使用方式和lazy一樣。
import AsyncComponent from './components/asyncComponent.js' const Home = AsyncComponent(() => import('./routes/Home')); const About = AsyncComponent(() => import('./routes/About'));
// async load 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 }) }) } } // component will be unmount componentWillUnmount() { // rewrite setState function, return nothing this.setState = () => { return } } render() { const { Component } = this.state if (Component) { return <Component {...this.props} /> } return null } } }
common業(yè)務(wù)代碼拆分
在完成基于路由的代碼分割后,仔細(xì)看包的大小,發(fā)現(xiàn)包的總大小反而變大了,2.5M增加為了3.5M。
從webpack分析工具中看到,罪魁禍?zhǔn)拙褪敲恳粋€單獨(dú)的路由代碼中都單獨(dú)打包了一份components、utils、locales一類的公共文件。
使用webapck的配置將common部分單獨(dú)打包解決。
components文件合并導(dǎo)出
示例是將components下的所有文件一起導(dǎo)出,其他文件同理
function readFileList(dir, filesList = []) { const files = fs.readdirSync(dir) files.forEach((item) => { let fullPath = path.join(dir, item) const stat = fs.statSync(fullPath) if (stat.isDirectory()) { // 遞歸讀取所有文件 readFileList(path.join(dir, item), filesList) } else { /\.js$/.test(fullPath) && filesList.push(fullPath) } }) return filesList } exports.commonPaths = readFileList(path.join(__dirname, '../src/components'), [])
webpack配置抽離common
import conf from '**'; module.exports = { entry: { common: conf.commonPaths, index: ['babel-polyfill', `./${conf.index}`], }, ... //其他配置 plugins:[ new webpack.optimize.CommonsChunkPlugin('common'), ... // other plugins ] }
在webpack3中使用CommonsChunkPlugin來提取第三方庫和公共模塊,傳入的參數(shù) common
是entrty已經(jīng)存在的chunk, 那么就會把公共模塊代碼合并到這個chunk上。
提取common后的代碼
將各個路由重復(fù)的代碼提取出來后,包的總大小又變?yōu)榱?.5M。多出了一個common的bundle文件。(common過大,其實(shí)還可以繼續(xù)拆分)
總結(jié)
webpack打包還有很多可以優(yōu)化的地方,另外不同webpack版本之間也有點(diǎn)差異,拆包思路就是提取公共,根據(jù)使用場景按需加載。
到此這篇關(guān)于Webpack3+React16代碼分割的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Webpack3+React16代碼分割內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React學(xué)習(xí)之受控組件與數(shù)據(jù)共享實(shí)例分析
這篇文章主要介紹了React學(xué)習(xí)之受控組件與數(shù)據(jù)共享,結(jié)合實(shí)例形式分析了React受控組件與組件間數(shù)據(jù)共享相關(guān)原理與使用技巧,需要的朋友可以參考下2020-01-01React?antd中setFieldsValu的簡便使用示例代碼
form.setFieldsValue是antd?Form組件中的一個方法,用于動態(tài)設(shè)置表單字段的值,它接受一個對象作為參數(shù),對象的鍵是表單字段的名稱,值是要設(shè)置的字段值,這篇文章主要介紹了React?antd中setFieldsValu的簡便使用,需要的朋友可以參考下2023-08-08詳解React項(xiàng)目中eslint使用百度風(fēng)格
這篇文章主要介紹了React項(xiàng)目中eslint使用百度風(fēng)格,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09Electron打包React生成桌面應(yīng)用方法詳解
這篇文章主要介紹了React+Electron快速創(chuàng)建并打包成桌面應(yīng)用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-12-12react-player實(shí)現(xiàn)視頻播放與自定義進(jìn)度條效果
本篇文章通過完整的代碼給大家介紹了react-player實(shí)現(xiàn)視頻播放與自定義進(jìn)度條效果,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2022-01-01教你使用vscode 搭建react-native開發(fā)環(huán)境
本文記錄如何使用vscode打造一個現(xiàn)代化的react-native開發(fā)環(huán)境,旨在提高開發(fā)效率和質(zhì)量。本文給大家分享我遇到的問題及解決方法,感興趣的朋友跟隨小編一起看看吧2021-07-07