Vue Cli3 项目打包优化

柔情只为你懂 2023-06-16 12:53 74阅读 0赞

一、新建项目

使用 vue-cli3 构建一个初始的Vue项目:Cli3 官方文档

因为使用了cli3,很多目录结构不见了,而相关配置是放在vue.config.js里面的,因此在根目录,新建一个vue.config.js

  1. module.exports = {}

二、正式优化

1、将 productionSourceMap 设为 false

(1) 在vue.config.jsmodule.exports写入:

  1. module.exports = {
  2. productionSourceMap: false
  3. }

2、图片压缩

vue正常打包之后一些图片文件很大,使打包体积很大,通过image-webpack-loader插件可将大的图片进行压缩从而缩小打包体积

(1) 先安装依赖:cnpm install image-webpack-loader --save-dev
(2) 在vue.config.jsmodule.exports写入:

  1. module.exports = {
  2. productionSourceMap: false,
  3. chainWebpack: config => {
  4. // ============压缩图片 start============
  5. config.module
  6. .rule('images')
  7. .use('image-webpack-loader')
  8. .loader('image-webpack-loader')
  9. .options({ bypassOnDebug: true })
  10. .end()
  11. // ============压缩图片 end============
  12. }
  13. }

3、cdn配置(可选)

(1) 在vue.config.js 最上边写入:

  1. // 是否为生产环境
  2. const isProduction = process.env.NODE_ENV !== 'development'
  3. // 本地环境是否需要使用cdn
  4. const devNeedCdn = false
  5. // cdn链接
  6. const cdn = {
  7. // cdn:模块名称和模块作用域命名(对应window里面挂载的变量名称)
  8. externals: {
  9. vue: 'Vue',
  10. vuex: 'Vuex',
  11. 'vue-router': 'VueRouter'
  12. },
  13. // cdn的css链接
  14. css: [],
  15. // cdn的js链接
  16. js: [
  17. 'https://cdn.staticfile.org/vue/2.6.10/vue.min.js',
  18. 'https://cdn.staticfile.org/vuex/3.0.1/vuex.min.js',
  19. 'https://cdn.staticfile.org/vue-router/3.0.3/vue-router.min.js'
  20. ]
  21. }

(2) 在vue.config.js module.exports chainWebpack中写入:

  1. // ============注入cdn start============
  2. config.plugin('html').tap(args => {
  3. // 生产环境或本地需要cdn时,才注入cdn
  4. if (isProduction || devNeedCdn) args[0].cdn = cdn
  5. return args
  6. })
  7. // ============注入cdn start============

(3) 在vue.config.js module.exports configureWebpack中写入:

  1. configureWebpack: config => {
  2. // 用cdn方式引入,则构建时要忽略相关资源
  3. if (isProduction || devNeedCdn) config.externals = cdn.externals
  4. }

(4) 当前配置的vue.config.js

  1. // 是否为生产环境
  2. const isProduction = process.env.NODE_ENV !== 'development'
  3. // 本地环境是否需要使用cdn
  4. const devNeedCdn = false
  5. // cdn链接
  6. const cdn = {
  7. // cdn:模块名称和模块作用域命名(对应window里面挂载的变量名称)
  8. externals: {
  9. vue: 'Vue',
  10. vuex: 'Vuex',
  11. 'vue-router': 'VueRouter'
  12. },
  13. // cdn的css链接
  14. css: [],
  15. // cdn的js链接
  16. js: [
  17. 'https://cdn.staticfile.org/vue/2.6.10/vue.min.js',
  18. 'https://cdn.staticfile.org/vuex/3.0.1/vuex.min.js',
  19. 'https://cdn.staticfile.org/vue-router/3.0.3/vue-router.min.js'
  20. ]
  21. }
  22. module.exports = {
  23. productionSourceMap: false,
  24. chainWebpack: config => {
  25. // ============压缩图片 start============
  26. config.module
  27. .rule('images')
  28. .use('image-webpack-loader')
  29. .loader('image-webpack-loader')
  30. .options({ bypassOnDebug: true })
  31. .end()
  32. // ============压缩图片 end============
  33. // ============注入cdn start============
  34. config.plugin('html').tap(args => {
  35. // 生产环境或本地需要cdn时,才注入cdn
  36. if (isProduction || devNeedCdn) args[0].cdn = cdn
  37. return args
  38. })
  39. // ============注入cdn start============
  40. },
  41. configureWebpack: config => {
  42. // 用cdn方式引入,则构建时要忽略相关资源
  43. if (isProduction || devNeedCdn) config.externals = cdn.externals
  44. }
  45. }

(5) 在public index.html 写入

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width,initial-scale=1.0" />
  7. <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
  8. <!-- 使用CDN的CSS文件 -->
  9. <% for (var i in htmlWebpackPlugin.options.cdn &&
  10. htmlWebpackPlugin.options.cdn.css) { %>
  11. <link
  12. href="<%= htmlWebpackPlugin.options.cdn.css[i] %>"
  13. rel="stylesheet"
  14. />
  15. <% } %>
  16. <!-- 使用CDN的CSS文件 -->
  17. <title>cli3_base</title>
  18. </head>
  19. <body>
  20. <noscript>
  21. <strong
  22. >We're sorry but cli3_base doesn't work properly without
  23. JavaScript enabled. Please enable it to continue.</strong
  24. >
  25. </noscript>
  26. <div id="app"></div>
  27. <!-- 使用CDN的JS文件 -->
  28. <% for (var i in htmlWebpackPlugin.options.cdn &&
  29. htmlWebpackPlugin.options.cdn.js) { %>
  30. <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
  31. <% } %>
  32. <!-- 使用CDN的JS文件 -->
  33. <!-- built files will be auto injected -->
  34. </body>
  35. </html>

(6) 重启项目npm run serve
(7) 在src/router.js修改

  1. Vue.use(Router)

改为

  1. if (!window.VueRouter) Vue.use(Router)

(8) 重新启动npm run serve即可,现在的配置是开发环境,在浏览器的Network JS里面是看不到的。若想查看,请将vue.config.js里面的

  1. // 本地环境是否需要使用cdn
  2. const devNeedCdn = false

改为

  1. // 本地环境是否需要使用cdn
  2. const devNeedCdn = true

然后再次重启npm run serve,然后浏览器查看Network JS

format_png

Network JS

4、代码压缩

(1) 安装依赖:cnpm i -D uglifyjs-webpack-plugin
(2) 在vue.config.js 最上边引入依赖

  1. // 代码压缩
  2. const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

(3) 在vue.config.js module.exports configureWebpack 里面新增

  1. // 生产环境相关配置
  2. if (isProduction) {
  3. // 代码压缩
  4. config.plugins.push(
  5. new UglifyJsPlugin({
  6. uglifyOptions: {
  7. //生产环境自动删除console
  8. compress: {
  9. warnings: false, // 若打包错误,则注释这行
  10. drop_debugger: true,
  11. drop_console: true,
  12. pure_funcs: ['console.log']
  13. }
  14. },
  15. sourceMap: false,
  16. parallel: true
  17. })
  18. )
  19. }

5、开启Gzip

(1) 安装依赖:cnpm install --save-dev compression-webpack-plugin
(2) 在vue.config.js 顶部引入依赖

  1. // gzip压缩
  2. const CompressionWebpackPlugin = require('compression-webpack-plugin')

(3) 在vue.config.js module.exports configureWebpack 里面新增,直接放在代码压缩下边即可

  1. // 生产环境相关配置
  2. if (isProduction) {
  3. // 代码压缩
  4. // ..................
  5. // gzip压缩
  6. const productionGzipExtensions = ['html', 'js', 'css']
  7. config.plugins.push(
  8. new CompressionWebpackPlugin({
  9. filename: '[path].gz[query]',
  10. algorithm: 'gzip',
  11. test: new RegExp(
  12. '\\.(' + productionGzipExtensions.join('|') + ')$'
  13. ),
  14. threshold: 10240, // 只有大小大于该值的资源会被处理 10240
  15. minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
  16. deleteOriginalAssets: false // 删除原文件
  17. })
  18. )
  19. }

6、公共代码抽离

(1) 在vue.config.js module.exports configureWebpack 里面新增,直接放在gzip压缩下边即可

  1. // 公共代码抽离
  2. config.optimization = {
  3. splitChunks: {
  4. cacheGroups: {
  5. vendor: {
  6. chunks: 'all',
  7. test: /node_modules/,
  8. name: 'vendor',
  9. minChunks: 1,
  10. maxInitialRequests: 5,
  11. minSize: 0,
  12. priority: 100
  13. },
  14. common: {
  15. chunks: 'all',
  16. test: /[\\/]src[\\/]js[\\/]/,
  17. name: 'common',
  18. minChunks: 2,
  19. maxInitialRequests: 5,
  20. minSize: 0,
  21. priority: 60
  22. },
  23. styles: {
  24. name: 'styles',
  25. test: /\.(sa|sc|c)ss$/,
  26. chunks: 'all',
  27. enforce: true
  28. },
  29. runtimeChunk: {
  30. name: 'manifest'
  31. }
  32. }
  33. }
  34. }

完整的vue.config.js

  1. // 代码压缩
  2. const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
  3. // gzip压缩
  4. const CompressionWebpackPlugin = require('compression-webpack-plugin')
  5. // 是否为生产环境
  6. const isProduction = process.env.NODE_ENV !== 'development'
  7. // 本地环境是否需要使用cdn
  8. const devNeedCdn = true
  9. // cdn链接
  10. const cdn = {
  11. // cdn:模块名称和模块作用域命名(对应window里面挂载的变量名称)
  12. externals: {
  13. vue: 'Vue',
  14. vuex: 'Vuex',
  15. 'vue-router': 'VueRouter'
  16. },
  17. // cdn的css链接
  18. css: [],
  19. // cdn的js链接
  20. js: [
  21. 'https://cdn.staticfile.org/vue/2.6.10/vue.min.js',
  22. 'https://cdn.staticfile.org/vuex/3.0.1/vuex.min.js',
  23. 'https://cdn.staticfile.org/vue-router/3.0.3/vue-router.min.js'
  24. ]
  25. }
  26. module.exports = {
  27. productionSourceMap: false,
  28. chainWebpack: config => {
  29. // ============压缩图片 start============
  30. config.module
  31. .rule('images')
  32. .use('image-webpack-loader')
  33. .loader('image-webpack-loader')
  34. .options({ bypassOnDebug: true })
  35. .end()
  36. // ============压缩图片 end============
  37. // ============注入cdn start============
  38. config.plugin('html').tap(args => {
  39. // 生产环境或本地需要cdn时,才注入cdn
  40. if (isProduction || devNeedCdn) args[0].cdn = cdn
  41. return args
  42. })
  43. // ============注入cdn start============
  44. },
  45. configureWebpack: config => {
  46. // 用cdn方式引入,则构建时要忽略相关资源
  47. if (isProduction || devNeedCdn) config.externals = cdn.externals
  48. // 生产环境相关配置
  49. if (isProduction) {
  50. // 代码压缩
  51. config.plugins.push(
  52. new UglifyJsPlugin({
  53. uglifyOptions: {
  54. //生产环境自动删除console
  55. compress: {
  56. warnings: false, // 若打包错误,则注释这行
  57. drop_debugger: true,
  58. drop_console: true,
  59. pure_funcs: ['console.log']
  60. }
  61. },
  62. sourceMap: false,
  63. parallel: true
  64. })
  65. )
  66. // gzip压缩
  67. const productionGzipExtensions = ['html', 'js', 'css']
  68. config.plugins.push(
  69. new CompressionWebpackPlugin({
  70. filename: '[path].gz[query]',
  71. algorithm: 'gzip',
  72. test: new RegExp(
  73. '\\.(' + productionGzipExtensions.join('|') + ')$'
  74. ),
  75. threshold: 10240, // 只有大小大于该值的资源会被处理 10240
  76. minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
  77. deleteOriginalAssets: false // 删除原文件
  78. })
  79. )
  80. // 公共代码抽离
  81. config.optimization = {
  82. splitChunks: {
  83. cacheGroups: {
  84. vendor: {
  85. chunks: 'all',
  86. test: /node_modules/,
  87. name: 'vendor',
  88. minChunks: 1,
  89. maxInitialRequests: 5,
  90. minSize: 0,
  91. priority: 100
  92. },
  93. common: {
  94. chunks: 'all',
  95. test: /[\\/]src[\\/]js[\\/]/,
  96. name: 'common',
  97. minChunks: 2,
  98. maxInitialRequests: 5,
  99. minSize: 0,
  100. priority: 60
  101. },
  102. styles: {
  103. name: 'styles',
  104. test: /\.(sa|sc|c)ss$/,
  105. chunks: 'all',
  106. enforce: true
  107. },
  108. runtimeChunk: {
  109. name: 'manifest'
  110. }
  111. }
  112. }
  113. }
  114. }
  115. }
  116. }

完成的 cli3_base 模板

Vue Cli3 项目配置

作者:MrHzq
链接:https://www.jianshu.com/p/476387c7fea3
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

发表评论

表情:
评论列表 (有 0 条评论,74人围观)

还没有评论,来说两句吧...

相关阅读

    相关 vue-cli4打包优化

    项目开始时webpack配置 vue-cli3以后,我们修改webpack配置,需要自己在项目根路径下创建vue.config.js文件。 一、 配置 proxy 跨域