第一步:安裝插件
npm i -D compression-webpack-plugin
第二步:引入。在文件vue.config.js里導入compression-webpack-plugin,並添加壓縮文件類型
const CompressionWebpackPlugin = require('compression-webpack-plugin') const productionGzipExtensions = ['js', 'css']
簡單方式:
configureWebpack: { plugins: [ new CompressionWebpackPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'), threshold: 10240, minRatio: 0.8 }) ] }
高級方式:
configureWebpack: config => { if (process.env.NODE_ENV === 'production') { // 配置productionGzip-高級的方式 // 配置參數詳解 // asset: 目標資源名稱。 [file] 會被替換成原始資源。[path] 會被替換成原始資源的路徑, [query] 會被替換成查詢字符串。默認值是 "[path].gz[query]"。 // algorithm: 可以是 function(buf, callback) 或者字符串。對於字符串來說依照 zlib 的算法(或者 zopfli 的算法)。默認值是 "gzip"。 // test: 所有匹配該正則的資源都會被處理。默認值是全部資源。 // threshold: 只有大小大於該值的資源會被處理。單位是 bytes。默認值是 0。 // minRatio: 只有壓縮率小於這個值的資源才會被處理。默認值是 0.8。 config.plugins.push( new CompressionWebpackPlugin({ filename: '[path].gz[query]', algorithm: 'gzip', test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'), threshold: 10240, minRatio: 0.8 }) ) } else { // 開發環境 } }
三、運行 npm run build 完成
四、完整vue.config.js文件配置
const path = require('path') const defaultSettings = require('./src/settings.js') // 導入compression-webpack-plugin const CompressionWebpackPlugin = require('compression-webpack-plugin') // 定義壓縮文件類型 const productionGzipExtensions = ['js', 'css'] function resolve(dir) { return path.join(__dirname, dir) } const name = defaultSettings.title || '我是title' // If your port is set to 80, // use administrator privileges to execute the command line. // For example, Mac: sudo npm run const port = 9528 // dev port // const port = 8200 // dev port // All configuration item explanations can be find in https://cli.vuejs.org/config/ module.exports = { publicPath: '/', // 輸出文件路徑,默認為dist outputDir: 'dist', // 放置生成的靜態資源 (js、css、img、fonts) 的 (相對於 outputDir 的) 目錄。 assetsDir: 'static', // 指定生成的 index.html 的輸出路徑 (相對於 outputDir)。也可以是一個絕對路徑 // indexPath: '', // 保存時 lint 代碼 lintOnSave: process.env.NODE_ENV === 'development', // 生產環境是否生成 sourceMap 文件 productionSourceMap: false, devServer: { host: '0.0.0.0', port: port, // 配置端口 open: true, // 自動開啟瀏覽器 compress: true, // 開啟壓縮 // 設置讓瀏覽器 overlay 同時顯示警告和錯誤 overlay: { warnings: false, errors: true }, // 設置請求代理 proxy: { '/api/*': { target: 'http://xx.xx.xx.xx:xxxx/', ws: true, changeOrigin: true, pathRewrite: { '^/api': '' // 請求地址 } } } }, configureWebpack: config => { config.name = name config.resolve.alias['@'] = resolve('src') config.performance = { hints: 'warning', //入口起點的最大體積 整數類型(以字節為單位) maxEntrypointSize: 50000000, //生成文件的最大體積 整數類型(以字節為單位 300k) maxAssetSize: 30000000, //只給出 js 文件的性能提示 assetFilter: function(assetFilename) { return assetFilename.endsWith('.js') } } if (process.env.NODE_ENV === 'production') { // 生產環境 // 編譯時刪除console.log config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true // 配置productionGzip-高級的方式 // 配置參數詳解 // asset: 目標資源名稱。 [file] 會被替換成原始資源。[path] 會被替換成原始資源的路徑, [query] 會被替換成查詢字符串。默認值是 "[path].gz[query]"。 // algorithm: 可以是 function(buf, callback) 或者字符串。對於字符串來說依照 zlib 的算法(或者 zopfli 的算法)。默認值是 "gzip"。 // test: 所有匹配該正則的資源都會被處理。默認值是全部資源。 // threshold: 只有大小大於該值的資源會被處理。單位是 bytes。默認值是 0。 // minRatio: 只有壓縮率小於這個值的資源才會被處理。默認值是 0.8。 config.plugins.push( new CompressionWebpackPlugin({ filename: '[path].gz[query]', algorithm: 'gzip', test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'), threshold: 10240, minRatio: 0.8 }) ) } else { // 開發環境 } }, chainWebpack(config) { config.plugins.delete('preload') // TODO: need test config.plugins.delete('prefetch') // TODO: need test // set svg-sprite-loader config.module.rule('svg').exclude.add(resolve('src/icons')).end() config.module.rule('icons').test(/\.svg$/).include.add(resolve('src/icons')).end().use('svg-sprite-loader').loader('svg-sprite-loader').options({ symbolId: 'icon-[name]' }).end() // set preserveWhitespace config.module.rule('vue').use('vue-loader').loader('vue-loader').tap(options => { options.compilerOptions.preserveWhitespace = true return options }).end() // https://webpack.js.org/configuration/devtool/#development config.when(process.env.NODE_ENV === 'development', config => config.devtool('cheap-source-map') ) config.when(process.env.NODE_ENV !== 'development', config => { config.plugin('ScriptExtHtmlWebpackPlugin').after('html').use('script-ext-html-webpack-plugin', [{ // `runtime` must same as runtimeChunk name. default is `runtime` inline: /runtime\..*\.js$/ }]).end() config.optimization.splitChunks({ chunks: 'all', cacheGroups: { libs: { name: 'chunk-libs', test: /[\\/]node_modules[\\/]/, priority: 10, chunks: 'initial' // only package third parties that are initially dependent }, elementUI: { name: 'chunk-elementUI', // split elementUI into a single package priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm }, commons: { name: 'chunk-commons', test: resolve('src/components'), // can customize your rules minChunks: 3, // minimum common number priority: 5, reuseExistingChunk: true } } }) config.optimization.runtimeChunk('single') } ) } }