前端性能优化【vuecli开启gzip压缩以及nginx的配置】

1.安装compression-webpack-plugin

npm install compression-webpack-plugin -D

2.vue.config.js配置gzip压缩

// 导入compression-webpack-plugin
const CompressionWebpackPlugin = require('compression-webpack-plugin');
// 定义压缩文件类型
const productionGzipExtensions = ['js', 'css']
module.exports = {
  configureWebpack: {
    plugins: [
      new CompressionWebpackPlugin({
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),//匹配文件名
        threshold: 10240,//对10K以上的数据进行压缩
        minRatio: 0.8,
        deleteOriginalAssets: false,//是否删除源文件
      })
    ]
  }
}

3.打包

npm run build

然后你就会发现神奇的事情发生了,体积整整小了几倍呀
在这里插入图片描述

4.服务器配置

紧接着,我们开启 nginx 服务端 gzip性能优化。找到nginx.conf配置文件,然后在文件中找到http ,接着添加如下代码,然后重启nginx服务(service nginx reloa)即可。

	##
	# Gzip Settings
	##
	gzip on; #开启或关闭gzip on off
	gzip_min_length 5k; #gzip压缩最小文件大小,超出进行压缩(自行调节)
	gzip_buffers 4 16k; #buffer 不用修改
	gzip_comp_level 8; #压缩级别:1-10,数字越大压缩的越好,时间也越长
	gzip_types text/plain application/x-javascript application/javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; #  压缩文件类型 
	gzip_vary on; # 和http头有关系,加个vary头,给代理服务器用的,有的浏览器支持压缩,有的不支持,所以避免浪费不支持的也压缩,所以根据客户端的HTTP头来判断,是否需要压缩

5.判断gzip压缩是否成功

前端性能优化【vuecli开启gzip压缩以及nginx的配置】_第1张图片

最后就是关于nginx的配置,如果是要自己配置的话,着实困难,所以我推荐大家使用这个网站对nginx进行配置,方便了很多

https://www.toolnb.com/gj/nginx_create/

你可能感兴趣的:(Vue学习)