• vue 打包性能优化总结


    所谓的性能优化在我看来就是访问速度的一个提升,那如何提升呢?下面是我的一些粗鄙的见解,请参考:

    用过vue 的开发者应该都晓得开发vue 项目随着项目开发愈久用到的插件越来越多的情况下打包后的chunk-vendors.js文件会越来越大,这个是最常见的导致页面加载缓慢文件之一:

    推荐两款常见的比较好用的分析工具:

    1、vue ui(可参考此博客vue ui 如何操作的

    2、webpack-bundle-analyzer打包文件分析工具webpack-bundle-analyzer

    chunk-vendor.js文件说明: 来自第三方插件,也就是node_modules/ 下所有用到的依赖包集合的打包文件的输出

    下面是个人项目vue,config.js部分配置文件供参考:有更好建议请留言赐教

    分包方式优化chunk-vendors.js 过大问题

    1. const { defineConfig } = require('@vue/cli-service');
    2. const path = require('path');
    3. // const useCDNs = require('./useCDNs');
    4. const webpack = require('webpack');
    5. const CompressionPlugin = require('compression-webpack-plugin');
    6. // const zlib = require('zlib');
    7. function resolve(dir) {
    8. return path.join(__dirname, dir);
    9. }
    10. module.exports = defineConfig({
    11. transpileDependencies: true,
    12. productionSourceMap: false,
    13. });
    14. module.exports = {
    15. // productionSourceMap: false,
    16. publicPath: '/',
    17. parallel: false,
    18. pwa: { // pwa 缓存处理
    19. iconPaths: {
    20. favicon32: 'favicon.ico',
    21. favicon16: 'favicon.ico',
    22. appleTouchIcon: 'favicon.ico',
    23. maskIcon: 'favicon.ico',
    24. msTileImage: 'favicon.ico',
    25. },
    26. },
    27. // 不输出 map 文件,以加速生产环境构建
    28. chainWebpack: (config) => {
    29. config.module
    30. .rule('md')
    31. .test(/\.md/)
    32. .use('vue-loader')
    33. .loader('vue-loader')
    34. .end()
    35. .use('vue-markdown-loader')
    36. .loader('vue-markdown-loader/lib/markdown-compiler')
    37. .options({
    38. raw: true,
    39. });
    40. config.module.rule('svg').exclude.add(resolve('src/icons')).end();
    41. config.module
    42. .rule('icons')
    43. .test(/\.svg$/)
    44. .include.add(resolve('src/icons'))
    45. .end()
    46. .use('svg-sprite-loader')
    47. .loader('svg-sprite-loader')
    48. .options({
    49. symbolId: 'icon-[name]',
    50. })
    51. .end();
    52. },
    53. configureWebpack: {
    54. resolve: {
    55. alias: {
    56. '@': path.resolve(__dirname, './src'),
    57. '@i': path.resolve(__dirname, './src/assets'),
    58. },
    59. },
    60. plugins: [
    61. new webpack.IgnorePlugin({
    62. resourceRegExp: /^\.\/locale$/,
    63. contextRegExp: /ElementPlus$/,
    64. }),
    65. new CompressionPlugin({ // 开启gzip压缩
    66. filename: '[path][base].gz',
    67. algorithm: 'gzip',
    68. test: /\.ts$|\.js$|\.css$|\.html$/,
    69. threshold: 10240,
    70. minRatio: 0.8,
    71. }),
    72. ],
    73. // 开启分离 js
    74. optimization: {
    75. runtimeChunk: 'single',
    76. splitChunks: {
    77. chunks: 'all',
    78. // maxInitialRequests: Infinity,
    79. // minSize: 20000,
    80. cacheGroups: {
    81. commons: {
    82. // split async commons chunk
    83. name: 'chunk-async-commons',
    84. minChunks: 2,
    85. priority: 40,
    86. chunks: 'async',
    87. },
    88. elementPlus: {
    89. name: 'chunk-elementPlus', // split elementUI into a single package
    90. priority: 30, // the weight needs to be larger than libs and app or it will be packaged into libs or app
    91. test: /[\\/]node_modules[\\/]_?element-plus(.*)/, // in order to adapt to cnpm
    92. },
    93. },
    94. },
    95. },
    96. },
    97. devServer: {
    98. //开发服务的一些处理
    99. },
    100. };

    依赖包通过cdn方式引入来优化项目打包过大问题:

    弊端: cdn外链资源请求慢的情况下,或者cdn当掉的话,那么项目启动肯定是会直接当掉或者一直加载中

    1. /** @file useCDNs.js */
    2. /** @typedef {string} ModuleName 模块名 */
    3. /** @typedef {string} ModuleRefer 模块在全局的引用 */
    4. /** @typedef {string} ElementTem 元素模板 */
    5. /** @typedef {{mod:ModuleName;refer:ModuleRefer;el:ElementTem}} CDNItem cdn 项目 */
    6. /**
    7. * cdn 使用函数。
    8. *
    9. * 此函数可以在指定开发环境中,指定某些模块作为外部依赖出现,并把准备好的第三方 cdn 模板以 `cdns` 参数通过 HtmlWebpackPlugin 插件插入到 `public/index.html` 文件中。
    10. * 你可以在 `public/index.html` 中使用 ejs 语法 <%= htmlWebpackPlugin.options.cdns %> 来插入准备好的 cdn。
    11. *
    12. * @param {import('webpack-chain')} config webpack-chain 实例
    13. * @param {CDNItem[]} cdns 传入需要使用的 cdn 数组
    14. * @param {string} env 什么环境下使用 cdn ,默认生产环境
    15. */
    16. module.exports = function useCDNs(config, cdns = [], env = 'production') {
    17. if (process.env.NODE_ENV !== env) return;
    18. config.externals(
    19. cdns.reduce((prev, v) => {
    20. prev[v.mod] = v.refer;
    21. return prev;
    22. }, {})
    23. );
    24. config.plugin('html').tap((args) => {
    25. args[0].cdns = cdns.map((v) => v.el).join('');
    26. return args;
    27. });
    28. };

    在vue.config.js 中使用useCDNs.js将需要用的cdn资源注入
    下面使用elemet-ui为例子:线上环境使用cdn方式,开发环境使用依赖方式、样式文件可以通过

    在main.js/main.ts 中引入

    1. const { defineConfig } = require('@vue/cli-service');
    2. const path = require('path');
    3. // const useCDNs = require('./useCDNs');
    4. const webpack = require('webpack');
    5. const CompressionPlugin = require('compression-webpack-plugin');
    6. // const zlib = require('zlib');
    7. function resolve(dir) {
    8. return path.join(__dirname, dir);
    9. }
    10. module.exports = defineConfig({
    11. transpileDependencies: true,
    12. productionSourceMap: false,
    13. });
    14. module.exports = {
    15. // productionSourceMap: false,
    16. publicPath: '/',
    17. parallel: false,
    18. pwa: {
    19. iconPaths: {
    20. favicon32: 'favicon.ico',
    21. favicon16: 'favicon.ico',
    22. appleTouchIcon: 'favicon.ico',
    23. maskIcon: 'favicon.ico',
    24. msTileImage: 'favicon.ico',
    25. },
    26. },
    27. // 不输出 map 文件,以加速生产环境构建
    28. chainWebpack: (config) => {
    29. // 只在生产环境使用 cdn
    30. useCDNs(config, {
    31. mod: 'moment',
    32. refer: 'moment',
    33. el: 'https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js',
    34. });
    35. configureWebpack: {
    36. resolve: {
    37. alias: {
    38. '@': path.resolve(__dirname, './src'),
    39. '@i': path.resolve(__dirname, './src/assets'),
    40. },
    41. },
    42. plugins: [
    43. new webpack.IgnorePlugin({
    44. resourceRegExp: /^\.\/locale$/,
    45. contextRegExp: /ElementPlus$/,
    46. }),
    47. new CompressionPlugin({
    48. filename: '[path][base].gz',
    49. algorithm: 'gzip',
    50. test: /\.ts$|\.js$|\.css$|\.html$/,
    51. threshold: 10240,
    52. minRatio: 0.8,
    53. }),
    54. ],
    55. // 开启分离 js
    56. optimization: { // 如果打包出的chunk-vender文件过大的话使用它
    57. runtimeChunk: 'single',
    58. splitChunks: {
    59. chunks: 'all',
    60. // maxInitialRequests: Infinity,
    61. // minSize: 20000,
    62. cacheGroups: {
    63. commons: {
    64. // split async commons chunk
    65. name: 'chunk-async-commons',
    66. minChunks: 2,
    67. priority: 40,
    68. chunks: 'async',
    69. },
    70. elementPlus: {
    71. name: 'chunk-elementPlus', // split elementUI into a single package
    72. priority: 30, // the weight needs to be larger than libs and app or it will be packaged into libs or app
    73. test: /[\\/]node_modules[\\/]_?element-plus(.*)/, // in order to adapt to cnpm
    74. },
    75. },
    76. },
    77. },
    78. },
    79. devServer: {
    80. },
    81. };

    简单记录有问题可私信解决 

  • 相关阅读:
    【Linux】Nginx安装使用负载均衡及动静分离(前后端项目部署),前端项目打包
    力扣234.回文链表
    【CSDN 竞赛—第10期】所有题目解法的思考和总结
    实战计算机网络02——物理层
    【Spring】Spring学习入门案例
    吴恩达机器学习系列课程笔记——第十二章:支持向量机(Support Vector Machines)
    计算机毕业设计Java健身生活系统(源码+mysql数据库+系统+lw文档)
    python 打包可执行文件-Nuitka详解
    塑料工厂5G智能制造数字孪生可视化平台,推进塑料行业数字化转型
    RN滚动选择组件react-native-wheel-picker-android
  • 原文地址:https://blog.csdn.net/zwt_guiji/article/details/125078917