1、导入压缩插件
import compressPlugin from "vite-plugin-compression";
2、vite配置压缩插件
plugins: [
vue(),
compressPlugin({
verbose: true, // 默认即可
disable: false, //开启压缩(不禁用),默认即可
deleteOriginFile: true, //删除源文件
threshold: 1, //压缩前最小文件大小
algorithm: 'gzip', //压缩算法
ext: '.gz', //文件类型
})
],
3、nginx配置(在http层级下) 这里要注意的 sendfile on;一定要开启, 不然的话无法使用gzip功能
include mime.types;
default_type application/octet-stream;
#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 logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
#开启gzip静态压缩功能
gzip_static on;
#gzip缓存大小
gzip_buffers 4 16k;
#gzip http版本
gzip_http_version 1.1;
#gzip 压缩级别 1-10
gzip_comp_level 5;
#gzip 压缩类型
gzip_types text/plain application/javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
# 是否在http header中添加Vary: Accept-Encoding,建议开启
gzip_vary on;
4、最后测试的时候最好不要留原来的js和css文件,不然都不知道gzip到底有没有开启成功
5、常见问题
5.1 nginx中配置gzip_static on提示nginx: [emerg] unknown directive “gzip_static“ in
1、此时可用在nginx的安装目录的sbin中使用./nginx -V查看当前nginx的配置信息,看有没有配置–with-http_gzip_static_module
## 配置
./configure --prefix=/usr/local/nginx --with-http_gzip_static_module
## 重新安装
make && make install
./nginx -V后的结果如下:
2、安装时make && make install报错
在安装Nginx输入make指令时报
src/os/unix/ngx_user.c: In function ‘ngx_libc_crypt’:
src/os/unix/ngx_user.c:36:7: error: ‘struct crypt_data’ has no member named ‘current_salt’
cd .current_salt[0] = ~salt[0];
^
src/http/ngx_http_script.c: In function ‘ngx_http_script_add_copy_code’:
src/http/ngx_http_script.c:698:18: error:cast between incompatible function types from ‘size_t (*)(ngx_http_script_engine_t )’ {aka ‘long unsigned int ()(struct )’} to ‘void ()(ngx_http_script_engine_t )’ {aka ‘void ()(struct *)’} [-Werror=cast-function-type]
code->code = (ngx_http_script_code_pt) ngx_http_script_copy_len_code;
解决办法:
1、vim /opt/nginx-1.12.2/src/os/unix/ngx_user.c
2、vim /opt/nginx-1.12.2/objs/Makefile 去掉-Werror
再重新make && make install 即可
参考:https://www.dandelioncloud.cn/article/details/1601473561787318273
https://blog.csdn.net/qq_24882601/article/details/129384746
https://blog.csdn.net/qq_45697992/article/details/120028370