vue cli3 打包压缩
实现过程
- 在项目中配置webpack
// vue.config.js
chainWebpack(config) {
config.plugin('compression').use(require('compression-webpack-plugin'), [{
filename: '[path].gz[query]', // 压缩过后的文件名
algorithm: 'gzip', // 压缩为gzip
test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i, // 匹配要进行压缩的文件格式
threshold: 10240, // 大于10kb的文件进行压缩
minRatio: 0.8, // 压缩率
deleteOriginalAssets: true // 删除源文件
}])
}
- 进行打包
// package.json
npm run build
首先如上配置webpack,然后进行打包,打包出来的文件(符合匹配条件的文件)就是压缩过的文件。例如:
- 打包前:app.js
- 打包后:app.js.gz
需要注意的是,打包出的index.html引入的js文件并没有添加gz后缀,例如:
- 不开启压缩的index.html:
<script type="text/javascript" src="static/js/app.js"></script>
- 开启压缩的index.html:
<script type="text/javascript" src="static/js/app.js"></script>
前后并没有变化,所以,如果想要在浏览器正确下载相对应的js文件,就需要服务端进行支持,这里以nginx为例 【关键】
// nginx.conf 这里指nginx的配置文件
server {
listen 8888;
server_name localhost;
location / {
root C:\Users\Administrator\Desktop\docphoto;
index index.html index.htm;
gzip_static on; // 只需要开启gzip_static即可
}
}
这里用到的是nginx的静态压缩,其实就是nginx可以通过ngx_http_gzip_module模块(默认安装)实现先压缩后输出,配置如上。
ngx_http_gzip_module 这个模块的作用是对于需要压缩的文件,直接读取已经压缩好的文件(文件名为加.gz),而不是动态压缩,对于不支持gzip的请求则读取原文件。
拓展
动态压缩是在服务端进行压缩,缺点是消耗服务器cpu的资源。【配置服务器】
静态压缩是在前端打包时进行压缩,通过webpack实现;然后服务端读取已经压缩好的文件传输给客户端,通过nginx实现。【前端配置webpack、配置服务器】
对于Apache部署的项目,没有找到支持静态压缩的模块
动态压缩配置:
- Apache配置
# 开启gzip模块
<IfModule mod_deflate.c>
DeflateCompressionLevel 6
SetOutputFilter DEFLATE
AddOutputFilter DEFLATE js css
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/x-javascript application/x-httpd-php
AddOutputFilterByType DEFLATE image/gif image/png image/jpe image/swf image/jpeg image/bmp
# 排除不需要压缩的文件
SetEnvIfNoCase Request_URI .(?:html|htm)$ no-gzip dont-varySetEnvIfNoCase
SetEnvIfNoCase Request_URI .(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
SetEnvIfNoCase Request_URI .(?:pdf|doc)$ no-gzip dont-vary
</IfModule>
- Nginx配置
server {
listen 8888;
server_name localhost;
location / {
root C:\Users\Administrator\Desktop\docphoto;
index index.html index.htm;
gzip on; // 只需要开启gzip即可
}
}