我的项目背景
最近我的项目里有个webpack版本较老的我的项目,因为降级和换框架临时不被leader层承受o(╥﹏╥)o,只能在现有条件进行优化。
webpack3 + react16
webpack v3配置查看
很显著我的项目的配置是从v1继承过去的,v1->v3的降级较为简单,参考官网https://webpack.js.org/migrat... 即可。
loaders变为rules不再反对链式写法的loader,json-loader不须要配置UglifyJsPlugin插件须要本人开启minimize
剖析现有包的问题
应用webpack-bundle-analyzer构建包后,如图
问题非常明显:
除了zxcvbn这个较大的包被拆出来,代码就简略的打包为了vender和app,文件很大。
动静import拆分vender
剖析vender的代码,某些大包,例如libphonenumber.js,应用场景不是很频繁,将它拆出来,当应用到相干个性时再申请。
参考react官网代码宰割指南,https://react.docschina.org/d...
import { PhoneNumberUtil } from 'google-libphonenumber'function usePhoneNumberUtil(){ // 应用PhoneNumberUtil}
批改为动静 import()
形式,then和async/await都反对用来获取异步数据
const LibphonenumberModule = () => import('google-libphonenumber')function usePhoneNumberUtil(){ LibphonenumberModule().then({PhoneNumberUtil} => { // 应用PhoneNumberUtil })}
当 Webpack 解析到该语法时,会主动进行代码宰割。
批改后的成果:
libphonenumber.js(1.chunk.js)从vender中拆分进去了,并且在我的项目理论运行中,只有当进入usePhoneNumberUtil流程时,才会向服务器申请libphonenumber.js文件。
基于路由的代码宰割
React.lazy
参考react官网代码宰割指南-基于路由的代码宰割,https://react.docschina.org/d...。
拆分前示例:
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主动拆分成了不同的文件,当切换路由时,才会拉取指标路由代码文件。
命名导出
该段援用自https://react.docschina.org/d...。React.lazy
目前只反对默认导出(default exports)。如果你想被引入的模块应用命名导出(named exports),你能够创立一个两头模块,来从新导出为默认模块。这能保障 tree shaking 不会出错,并且不用引入不须要的组件。
// ManyComponents.jsexport const MyComponent = /* ... */;export const MyUnusedComponent = /* ... */;
// MyComponent.jsexport { MyComponent as default } from "./ManyComponents.js";
// MyApp.jsimport React, { lazy } from 'react';const MyComponent = lazy(() => import("./MyComponent.js"));
本人实现AsyncComponent
React.lazy包裹的懒加载路由组件,必须要增加Suspense。如果不想强制应用,或者须要自在扩大lazy的实现,能够定义实现AsyncComponent,应用形式和lazy一样。
import AsyncComponent from './components/asyncComponent.js'const Home = AsyncComponent(() => import('./routes/Home'));const About = AsyncComponent(() => import('./routes/About'));
// async load componentfunction 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业务代码拆分
在实现基于路由的代码宰割后,认真看包的大小,发现包的总大小反而变大了,2.5M减少为了3.5M。
从webpack剖析工具中看到,罪魁祸首就是每一个独自的路由代码中都独自打包了一份components、utils、locales一类的公共文件。
应用webapck的配置将common局部独自打包解决。
components文件合并导出
示例是将components下的所有文件一起导出,其余文件同理
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来提取第三方库和公共模块,传入的参数common
是entrty曾经存在的chunk, 那么就会把公共模块代码合并到这个chunk上。
提取common后的代码
将各个路由反复的代码提取进去后,包的总大小又变为了2.5M。多出了一个common的bundle文件。(common过大,其实还能够持续拆分)
总结
webpack打包还有很多能够优化的中央,另外不同webpack版本之间也有点差别,拆包思路就是提取公共,依据应用场景按需加载。