Vue Cli 項目打包體積過大,優化vue項目體積


最新打包vue cli 4.5 項目時,體積盡然達到了9M,頁面訪問的速度,因此進行嘗試進行優化,最終壓縮到 968k ,效果明顯。下面是優化方法。

首先新建文件'vue.config.js',放在項目根目錄下,與package.json在同一級目錄下

1.BundleAnalyzer 

作用:展示打包圖形化信息,會打開一個html頁面,幫助自己分析哪些文件過大,可針對其進行優化,上線前 注釋掉

 安裝 webpack-bundle-analyzer 插件 

npm install webpack-bundle-analyzer --save-dev

 在 vue.config.js: 里面:

 1 // 引入
 2 const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
 3  
 4 // 展示圖形化信息
 5 chainWebpack: config => {
 6   config
 7       .plugin('webpack-bundle-analyzer')
 8       .use(BundleAnalyzerPlugin)
 9 }

 

2.抽離 css 支持按需加載

  安裝 mini-css-extract-plugin 插件

 npm install mini-css-extract-plugin -D

在 vue.config.js里面:

1 chainWebpack: config => {
2   let miniCssExtractPlugin = new MiniCssExtractPlugin({
3     filename: 'assets/[name].[hash:8].css',
4     chunkFilename: 'assets/[name].[hash:8].css'
5   })
6   config.plugin('extract-css').use(miniCssExtractPlugin)
7 }

 3.圖片按需加載

安裝image-webpack-loader插件

npm install image-webpack-loader -D 

在 vue.config.js里面:  

1 config.module.rule('images')
2     .test(/\.(png|jpe?g|gif|webp)(\?.*)?$/)
3     .use('image-webpack-loader')
4     .loader('image-webpack-loader')
5     .options({
6       bypassOnDebug: true
7     })
8 .end()

 

4.gzip壓縮代碼 

安裝 compression-webpack-plugin 插件 

 npm install compression-webpack-plugin -D

在 vue.config.js里面: 

 1 const CompressionWebpackPlugin = require('compression-webpack-plugin');
 2  
 3 // 開啟gzip壓縮
 4   config.plugins.push(
 5     new CompressionWebpackPlugin(
 6       {
 7         filename: info => {
 8           return `${info.path}.gz${info.query}`
 9         },
10         algorithm: 'gzip',
11         threshold: 10240, // 只有大小大於該值的資源會被處理 10240
12         test: new RegExp('\\.(' + ['js'].join('|') + ')$'
13         ),
14         minRatio: 0.8, // 只有壓縮率小於這個值的資源才會被處理
15         deleteOriginalAssets: false // 刪除原文件
16       }
17     )
18 )

5.element-ui 按需加載

安裝 babel-plugin-component 插件

npm install babel-plugin-component --save-dev

在 babel.config.js里面:

 1 module.exports = {
 2   presets: [
 3     '@vue/app'
 4   ],
 5   plugins: [
 6     [
 7       "component",
 8       {
 9         libraryName: "element-ui",
10         styleLibraryName: "theme-chalk"
11       }
12     ]
13   ]
14 }

6.Echarts 按需加載

安裝 babel-plugin-equire 插件:

npm install babel-plugin-equire -D

創建 echarts.js:

1  // eslint-disable-next-line
2    const echarts = equire([
3     // 寫上你需要的 echarts api
4     "tooltip",
5     "line"
6   ]);
7 export default echarts;

 在 babel.config.js里面:

 1 module.exports = {
 2   presets: [
 3     '@vue/app'
 4   ],
 5   plugins: [
 6     [
 7       "component",
 8       {
 9         libraryName: "element-ui",
10         styleLibraryName: "theme-chalk"
11       }
12     ],
13     "equire"
14   ]
15 }

具體頁面應用:

1  // 直接引用
2  import echarts from '@/lib/util/echarts.js' 
3  
4  this.myChart = echarts.init(this.$refs.chart)

 

 7.lodash 按需加載

安裝 lodash-webpack-plugin 插件

 npm install lodash-webpack-plugin --save-dev

在 babel.config.js里面:

 1 module.exports = {
 2   presets: [
 3     '@vue/app'
 4   ],
 5   plugins: [
 6     [
 7       "component",
 8       {
 9         libraryName: "element-ui",
10         styleLibraryName: "theme-chalk"
11       }
12     ],
13     "lodash",
14     "equire"
15   ]
16 }

 在 vue.config.js里面:

1 const LodashModuleReplacementPlugin = require("lodash-webpack-plugin");
2  
3 chainWebpack: config => {
4     config
5     .plugin("loadshReplace")
6     .use(new LodashModuleReplacementPlugin());
7 
8 }

8.prefetch 和 preload

刪除無用的插件,避免加載多余的資源(如果不刪除的話,則會在 index.html 里面加載 無用的 js 文件)

chainWebpack: config => {
    // 移除prefetch插件,避免加載多余的資源
    config.plugins.delete('prefetch')
    / 移除 preload 插件,避免加載多余的資源
    config.plugins.delete('preload');
}

總結

通過如上的幾個步驟,能夠很好地優化項目打包體積大小,從而優化項目。

vue.config.js文件中完整代碼

  1 onst MiniCssExtractPlugin = require('mini-css-extract-plugin');
  2 const CompressionWebpackPlugin = require('compression-webpack-plugin');
  3 const LodashModuleReplacementPlugin = require("lodash-webpack-plugin");
  4  
  5 module.exports = {
  6   productionSourceMap: false, // 關閉生產環境的 source map
  7   lintOnSave: false,
  8   publicPath: process.env.VUE_APP_PUBLIC_PATH,
  9   devServer: {
 10     host: "localhost",
 11     port: 3002,
 12     proxy: {
 13       '/api': {
 14         target: "https://tapi.quanziapp.com/api/",
 15         ws: true,
 16         changeOrigin: true,
 17         pathRewrite: {
 18           '^/api': ''
 19         }
 20       },
 21     }
 22   },
 23  
 24   chainWebpack: config => {
 25  
 26     // 移除 prefetch 插件
 27     config.plugins.delete('prefetch');
 28     // 移除 preload 插件,避免加載多余的資源
 29     config.plugins.delete('preload');
 30  
 31     config.optimization.minimize(true);
 32  
 33     config.optimization.splitChunks({
 34       chunks: 'all'
 35     })
 36  
 37     config
 38       .plugin('webpack-bundle-analyzer')
 39       .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
 40  
 41     if (process.env.NODE_ENV !== 'development') {
 42  
 43       let miniCssExtractPlugin = new MiniCssExtractPlugin({
 44         filename: 'assets/[name].[hash:8].css',
 45         chunkFilename: 'assets/[name].[hash:8].css'
 46       })
 47       config.plugin('extract-css').use(miniCssExtractPlugin)
 48       config.plugin("loadshReplace").use(new LodashModuleReplacementPlugin());
 49  
 50       config.module.rule('images')
 51         .test(/\.(png|jpe?g|gif|webp)(\?.*)?$/)
 52         .use('image-webpack-loader')
 53         .loader('image-webpack-loader')
 54         .options({
 55           bypassOnDebug: true
 56         })
 57         .end()
 58         .use('url-loader')
 59         .loader('file-loader')
 60         .options({
 61           name: 'assets/[name].[hash:8].[ext]'
 62         }).end()
 63       config.module.rule('svg')
 64         .test(/\.(svg)(\?.*)?$/)
 65         .use('file-loader')
 66         .loader('file-loader')
 67         .options({
 68           name: 'assets/[name].[hash:8].[ext]'
 69         })
 70     }
 71   },
 72   configureWebpack: config => {
 73     // config.plugins.push(["equire"]);
 74  
 75     if (process.env.NODE_ENV !== 'development') {
 76       config.output.filename = 'assets/[name].[hash:8].js'
 77       config.output.chunkFilename = 'assets/[name].[hash:8].js'
 78     }
 79     // 公共代碼抽離
 80     config.optimization = {
 81       // 分割代碼塊
 82       splitChunks: {
 83         cacheGroups: {
 84           //公用模塊抽離
 85           common: {
 86             chunks: 'initial',
 87             minSize: 0, //大於0個字節
 88             minChunks: 2, //抽離公共代碼時,這個代碼塊最小被引用的次數
 89           },
 90           //第三方庫抽離
 91           vendor: {
 92             priority: 1, //權重
 93             test: /node_modules/,
 94             chunks: 'initial',
 95             minSize: 0, //大於0個字節
 96             minChunks: 2, //在分割之前,這個代碼塊最小應該被引用的次數
 97           },
 98         },
 99       }
100     }
101     // 開啟gzip壓縮
102     config.plugins.push(
103       new CompressionWebpackPlugin(
104         {
105           filename: info => {
106             return `${info.path}.gz${info.query}`
107           },
108           algorithm: 'gzip',
109           threshold: 10240, // 只有大小大於該值的資源會被處理 10240
110           test: new RegExp('\\.(' + ['js'].join('|') + ')$'
111           ),
112           minRatio: 0.8, // 只有壓縮率小於這個值的資源才會被處理
113           deleteOriginalAssets: false // 刪除原文件
114         }
115       )
116     )
117   },
118   css: {
119     extract: true,
120     sourceMap: false,
121     loaderOptions: {
122       sass: {
123       },
124     },
125   },
126 }
127  
 ————————————————
版權聲明:本文為CSDN博主「木不是丁」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。 原文鏈接:https://blog.csdn.net/D102601560/article/details/109025683


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM