档案系统现状

打包后就两个 chunk 文件。 一个来自我们写的代码,src 一个来自第三方模块的文件,node_modules

档案系统的依赖分析情况。

使用 webpack-bundle-analyzer 插件

image.png
image.pngimage.png
image.png
gzip 压缩后,第三方模块一起打包起来有 1.62 MB,请求一个这么大的包,耗时很大。
打算对它进行分包。

利用 splitChunk 进行分包

档案系统是给档案馆用的,对方的电脑、网络情况就 20M 宽带,希望首次登录能在 1s 内呈现画面,2s 内能交互为目标。
假设现在网络情况是发送一个 http 请求 400kb 内容不会卡。

设置 minSize 和 maxSize 进行分包

  1. // 原先配置
  2. module.exports = {
  3. splitChunks: {
  4. chunks: 'all',
  5. name: false,
  6. },
  7. }
  8. // 修改后的配置
  9. module.exports = {
  10. splitChunks: {
  11. chunks: 'all',
  12. minSize: 400000, // 打包后的资源,gzip 后文件大小要小于 400 kb
  13. maxSize: 600000, // 如果资源大于 600kb,则继续拆分资源
  14. name: false,
  15. },
  16. }

image.png
我承认这样分包有点太暴力了,我们把一些比较大的几个包,把它拿出来就好了。

设置 cacheGroup 按组分包

我们拆出 @tensorflow、xlsx,video 这个三个包。

  1. module.exports = {
  2. splitChunks: {
  3. chunks: 'all',
  4. name: false,
  5. cacheGroups: {
  6. tensorflow: {
  7. test: /[\\/]node_modules[\\/](@tensorflow)[\\/]/,
  8. chunks: 'all',
  9. name: 'tensorflow',
  10. },
  11. src: {
  12. test: /[\\/]src[\\/]/,
  13. chunks: 'all',
  14. name: 'src',
  15. },
  16. xlsx: {
  17. test: /[\\/]node_modules[\\/](xlsx)[\\/]/,
  18. chunks: 'all',
  19. enforce: true,
  20. name: 'xlsx'
  21. },
  22. video: {
  23. test: /[\\/]node_modules[\\/](video.js)[\\/]/,
  24. chunks: 'all',
  25. enforce: true,
  26. name: 'video'
  27. },
  28. pdf: {
  29. test: /[\\/]node_modules[\\/]@bundled-es-modules[\\/](pdfjs-dist)[\\/]/,
  30. chunks: 'all',
  31. enforce: true,
  32. name: 'pdf'
  33. }
  34. },
  35. },
  36. }

image.png
image.pngimage.png
image.png

给脚本添加 async、defer属性

image.png
我们分包完成后,由于页面是需要边解析边执行脚本。
所以首屏渲染 和 最大绘制内容时间都很久。所以我们把一些不会很快用到的脚本添加上 defer 属性。
比如第三方脚本,video、xlsx 之类的。
使用一个包npm install --save-dev script-ext-html-webpack-plugin

  1. module.exports = {
  2. plugins: [
  3. new HtmlWebpackPlugin({...}),
  4. new ScriptExtHtmlWebpackPlugin({
  5. defer: /(xlsx|video|tensorflow|pdf)/
  6. }),
  7. ]
  8. }

image.png

非首屏界面使用懒加载

那么不是首屏的资源使用懒加载。

参考资料

《SplitChunksPlugin——webpack 官网》
《Webpack之SplitChunks插件用法详解》
《script-ext-html-webpack-plugin》