vue-cli3使用gzip解決前端打包資源文件過大的問題

本方案適用于vue-router-history模式的前后端分離項(xiàng)目,前端項(xiàng)目部署在nginx下。

環(huán)境

Node 8.11.4
Vue-CLI 4.x
Nginx 1.15.7

安裝插件

npm install compression-webpack-plugin

配置vue.config.js

先引入插件

const CompressionPlugin = require('compression-webpack-plugin');

在module.exports中添加下方module.exports內(nèi)的代碼。

module.exports = {

/*從這里開始添加*/
    configureWebpack: config => {
        if(process.env.NODE_ENV === 'production'){
            return {
                plugins: [new CompressionPlugin({
                    test: /\.js$|\.html$|\.css/,
                    threshold: 10240,
                    deleteOriginalAssets: false
                })]
            }
        }
    }
/*到這里結(jié)束*/

}; 

配置Nginx

我這里router是history模式的,在之前的博客中提到過相應(yīng)的配置方法。
我這里是域名下只有一個(gè)項(xiàng)目的配置,如果你的環(huán)境是一個(gè)域名多個(gè)項(xiàng)目,可以適當(dāng)對齊調(diào)整,原理是一樣的。

請參考下方代碼對之前項(xiàng)目所配置的location進(jìn)行修改

之前的

location / {    
           root e:\workgit\abc;
    error_page 405 =200 http://$host:8085/$request_uri; 
           index  index.html index.htm;
           try_files $uri $uri/ @rewrites; 
        } 
        
        location @rewrites {
        rewrite ^(.*)$ /index.html last;
    }

更新后

location / {    
           root e:\workgit\abc;
    error_page 405 =200 http://$host:8085/$request_uri; 
                gzip on;
                gzip_static on;
                gzip_http_version 1.1;
                gzip_comp_level 3;
                gzip_types text/plain application/json application/x-javascript application/css application/xml application/xml+rss text/javascript application/x-httpd-php image/jpeg image/gif image/png image/x-ms-bmp;
           index  index.html index.htm;
           try_files $uri $uri/ @rewrites; 
        } 
        
        location @rewrites {
        rewrite ^(.*)$ /index.html last;
    }

請不要無腦復(fù)制。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容