您的位置:首页 > Web前端 > React

Webpack3+React16代码分割的实现

2021-03-05 04:06 811 查看

项目背景

最近项目里有个webpack版本较老的项目,由于升级和换框架暂时不被leader层接受o(╥﹏╥)o,只能在现有条件进行优化。

webpack3 + react16

webpack v3配置检查

很明显项目的配置是从v1继承过来的,v1->v3的升级较为简单,参考官网https://webpack.js.org/migrate/3/即可。

loaders变为rules
不再支持链式写法的loader,json-loader不需要配置
UglifyJsPlugin插件需要自己开启minimize

分析现有包的问题

使用webpack-bundle-analyzer构建包后,如图

问题非常明显:

除了zxcvbn这个较大的包被拆出来,代码就简单的打包为了vender和app,文件很大。

动态import拆分vender

分析vender的代码,某些大包,例如libphonenumber.js,使用场景不是很频繁,将它拆出来,当使用到相关特性时再请求。

参考react官方代码分割指南, https://react.docschina.org/docs/code-splitting.html#import

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/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自动拆分成了不同的文件,当切换路由时,才会拉取目标路由代码文件。

命名导出

该段引用自 https://react.docschina.org/docs/code-splitting.html#named-exports

React.lazy 目前只支持默认导出(default exports)。如果你想被引入的模块使用命名导出(named exports),你可以创建一个中间模块,来重新导出为默认模块。这能保证 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"));

自己实现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 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业务代码拆分

在完成基于路由的代码分割后,仔细看包的大小,发现包的总大小反而变大了,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版本之间也有点差异,拆包思路就是提取公共,根据使用场景按需加载。

到此这篇关于Webpack3+React16代码分割的实现的文章就介绍到这了,更多相关Webpack3+React16代码分割内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息