vue cli3 打包压缩

实现过程

  • 在项目中配置webpack
  1. // vue.config.js
  2. chainWebpack(config) {
  3. config.plugin('compression').use(require('compression-webpack-plugin'), [{
  4. filename: '[path].gz[query]', // 压缩过后的文件名
  5. algorithm: 'gzip', // 压缩为gzip
  6. test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i, // 匹配要进行压缩的文件格式
  7. threshold: 10240, // 大于10kb的文件进行压缩
  8. minRatio: 0.8, // 压缩率
  9. deleteOriginalAssets: true // 删除源文件
  10. }])
  11. }
  • 进行打包
  1. // package.json
  2. npm run build

首先如上配置webpack,然后进行打包,打包出来的文件(符合匹配条件的文件)就是压缩过的文件。例如:

  • 打包前:app.js
  • 打包后:app.js.gz

需要注意的是,打包出的index.html引入的js文件并没有添加gz后缀,例如:

  • 不开启压缩的index.html:
  1. <script type="text/javascript" src="static/js/app.js"></script>
  • 开启压缩的index.html:
  1. <script type="text/javascript" src="static/js/app.js"></script>

前后并没有变化,所以,如果想要在浏览器正确下载相对应的js文件,就需要服务端进行支持,这里以nginx为例 【关键】

  1. // nginx.conf 这里指nginx的配置文件
  2. server {
  3. listen 8888;
  4. server_name localhost;
  5. location / {
  6. root C:\Users\Administrator\Desktop\docphoto;
  7. index index.html index.htm;
  8. gzip_static on; // 只需要开启gzip_static即可
  9. }
  10. }

这里用到的是nginx的静态压缩,其实就是nginx可以通过ngx_http_gzip_module模块(默认安装)实现先压缩后输出,配置如上。

ngx_http_gzip_module 这个模块的作用是对于需要压缩的文件,直接读取已经压缩好的文件(文件名为加.gz),而不是动态压缩,对于不支持gzip的请求则读取原文件。

拓展

动态压缩是在服务端进行压缩,缺点是消耗服务器cpu的资源。【配置服务器】
静态压缩是在前端打包时进行压缩,通过webpack实现;然后服务端读取已经压缩好的文件传输给客户端,通过nginx实现。【前端配置webpack、配置服务器】

对于Apache部署的项目,没有找到支持静态压缩的模块

动态压缩配置:

  1. Apache配置
  1. # 开启gzip模块
  2. <IfModule mod_deflate.c>
  3. DeflateCompressionLevel 6
  4. SetOutputFilter DEFLATE
  5. AddOutputFilter DEFLATE js css
  6. AddOutputFilterByType DEFLATE text/html text/plain text/xml application/x-javascript application/x-httpd-php
  7. AddOutputFilterByType DEFLATE image/gif image/png image/jpe image/swf image/jpeg image/bmp
  8. # 排除不需要压缩的文件
  9. SetEnvIfNoCase Request_URI .(?:html|htm)$ no-gzip dont-varySetEnvIfNoCase
  10. SetEnvIfNoCase Request_URI .(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
  11. SetEnvIfNoCase Request_URI .(?:pdf|doc)$ no-gzip dont-vary
  12. </IfModule>
  1. Nginx配置
  1. server {
  2. listen 8888;
  3. server_name localhost;
  4. location / {
  5. root C:\Users\Administrator\Desktop\docphoto;
  6. index index.html index.htm;
  7. gzip on; // 只需要开启gzip即可
  8. }
  9. }