gzip 从15秒到700毫秒的前端项目优化解决方案

作者:jcmp      发布时间:2021-04-24      浏览量:0
一、gzip 优化gzip 优化前gzi

一、gzip 优化

gzip 优化前

gzip 优化后

项目地址 http://mrlishaohai.com/

二、前端配置(使用 vue-cli3.x)

webpack 官网 compression-webpack-plugin。

$ npm i compression-webpack-plugin --save-dev。

const productionGzipExtensions = /\.(js|css|html|svg)$/i;const CompressionWebpackPlugin = require('compression-webpack-plugin');module.exports = { configureWebpack: config => { // https://cli.vuejs.org/zh/guide/webpack.html#%E7%AE%80%E5%8D%95%E7%9A%84%E9%85%8D%E7%BD%AE%E6%96%B9%E5%BC%8F if (process.env.NODE_ENV === 'production') { // 为生产环境修改配置... // config.output.filename = 'assets/js/[name].[contenthash:8].min.js'; // config.output.chunkFilename // = 'assets/js/[name].[contenthash:8].min.js'; config.plugins = [ ...config.plugins, new CompressionWebpackPlugin({ filename: '[path].gz[query]', algorithm: 'gzip', test: productionGzipExtensions, threshold: 2048, minRatio: 0.8 }) ]; } else { // 为开发环境修改配置... config.devtool = 'cheap-module-eval-source-map'; } }};

三、nginx 开启 gzip 优化

1.把阿里云服务上的文件拷贝到本地

# 把阿里云服务上的文件拷贝到本地scp -r root@123.56.21.102:/etc/nginx/nginx.conf ./

2.nginx.conf 默认配置

# For more information on configuration, see:# * Official English Documentation: http://nginx.org/en/docs/# * Official Russian Documentation: http://nginx.org/ru/docs/user nginx;worker_processes auto;error_log /var/log/nginx/error.log;pid /run/nginx.pid;# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.include /usr/share/nginx/modules/*.conf;events { worker_connections 1024;}http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; server { listen 80 default_server; server_name localhost; location / { proxy_pass http://127.0.0.1:8090; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } }}

4. 把修改后的文件重新上传到阿里云服务

win 电脑建议使用 git bash 进行以下命令的操作

# 1. 上传到阿里云服务默认目录,使用 cd ~ 可以切换到对应目录scp -r ./nginx.conf root@123.56.21.102:./# 2. 使用ssh登录阿里云服务器, 输入以下命令按照提示输入密码就行ssh root@123.56.21.102# 3. 切换到默认 ~目录cd ~# 4. nginx配置文件的默认路径,/etc/nginx/nginx.conf# 备份nginx.conf文件# 把默认配置文件拷贝出来 并重命名为nginx.conf.backupcp /etc/nginx/nginx.conf ./nginx.conf.backup# 5. 把nginx修改后的配置文件再拷贝回去cp ./nginx.conf /etc/nginx/nginx.conf# cp: overwrite '/etc/nginx/nginx.conf'? y# 6.重启nginxsystemctl restart nginx。