uniapp(vue2)打包h5开启gzip

331 阅读1分钟

记录

image.png

注意: uniapp的h5开启tree-shanking,打包后的chunk-vendors.xxx.js还是很大.

开启gzip压缩,浏览器打开content-encoding显示

image.png

清理缓存重新请求

image.png

uniapp开启压缩gzip

npm install compression-webpack-plugin@3.1.0 -D

根目录新建vue.config.js

const isProduction = process.env.NODE_ENV === 'production'
// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin') // 开启压缩
module.exports = {
  productionSourceMap: false,
  configureWebpack: config => {
    if (isProduction) {
      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: /\.js$|\.html$|.\css/,
          threshold: 10240, // 只有大小大于该值的资源会被处理 10240
          minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
          deleteOriginalAssets: false // 删除原文件
        })
      )
    }
  }
}

点击发行之后

image.png

配置nginx访问

worker_processes  1;

error_log  logs/error.log  info;

pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile      on;
 
    keepalive_timeout  65;


# 启用gzip压缩,提高用户访问速度
    gzip on;
    gzip_static on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 2;
    gzip_types text/plain application/css application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
    gzip_vary on;

    server {
		listen       8084;
        server_name  localhost;
		location / {
				root   html;
				index  index.html index.htm;
		}
		error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

    include conf.d/*.conf;
}

image.png

通过最终的对比,确实加快了速度

如果还是慢,通过分析来判断进行处理

npm install webpack-bundle-analyzer -D

module.exports = {
  productionSourceMap: false,
  lintOnSave: false, // 关闭eslint
  chainWebpack: config => {
    config
      .plugin('webpack-bundle-analyzer')
      .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
  }
}

默认开启服务,显示占用数据

image.png