集成compression-webpack-plugin插件实现打包Gzip压缩 nginx 配置

集成compression-webpack-plugin插件实现打包Gzip压缩 nginx 配置

一,配置vue项目打包生成gzip

1.1 package.json 添加如下配置

在这里插入图片描述
参考 若依 配置:

{
    
    
  "name": "ruoyi",
  "version": "3.8.6",
  "description": "若依管理系统",
  "author": "若依",
  "license": "MIT",
  "scripts": {
    
    
    "dev": "vue-cli-service serve",
    "build:prod": "vue-cli-service build",
    "build:stage": "vue-cli-service build --mode staging",
    "preview": "node build/index.js --preview",
    "lint": "eslint --ext .js,.vue src"
  },
  "husky": {
    
    
    "hooks": {
    
    
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    
    
    "src/**/*.{js,vue}": [
      "eslint --fix",
      "git add"
    ]
  },
  "keywords": [
    "vue",
    "admin",
    "dashboard",
    "element-ui",
    "boilerplate",
    "admin-template",
    "management-system"
  ],
  "repository": {
    
    
    "type": "git",
    "url": "https://gitee.com/y_project/RuoYi-Vue.git"
  },
  "dependencies": {
    
    
    "@riophae/vue-treeselect": "0.4.0",
    "axios": "0.24.0",
    "clipboard": "2.0.8",
    "core-js": "3.25.3",
    "echarts": "5.4.0",
    "element-ui": "2.15.13",
    "file-saver": "2.0.5",
    "fuse.js": "6.4.3",
    "highlight.js": "9.18.5",
    "js-beautify": "1.13.0",
    "js-cookie": "3.0.1",
    "jsencrypt": "3.0.0-rc.1",
    "nprogress": "0.2.0",
    "quill": "1.3.7",
    "screenfull": "5.0.2",
    "sortablejs": "1.10.2",
    "vue": "2.6.12",
    "vue-count-to": "1.0.13",
    "vue-cropper": "0.5.5",
    "vue-meta": "2.4.0",
    "vue-router": "3.4.9",
    "vuedraggable": "2.24.3",
    "vuex": "3.6.0"
  },
  "devDependencies": {
    
    
    "@vue/cli-plugin-babel": "4.4.6",
    "@vue/cli-plugin-eslint": "4.4.6",
    "@vue/cli-service": "4.4.6",
    "babel-eslint": "10.1.0",
    "babel-plugin-dynamic-import-node": "2.3.3",
    "chalk": "4.1.0",
    "compression-webpack-plugin": "5.0.2",
    "connect": "3.6.6",
    "eslint": "7.15.0",
    "eslint-plugin-vue": "7.2.0",
    "lint-staged": "10.5.3",
    "runjs": "4.4.2",
    "sass": "1.32.13",
    "sass-loader": "10.1.1",
    "script-ext-html-webpack-plugin": "2.1.5",
    "svg-sprite-loader": "5.1.1",
    "vue-template-compiler": "2.6.12"
  },
  "engines": {
    
    
    "node": ">=8.9",
    "npm": ">= 3.0.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]
}

1.2修改vue.config.js

在这里插入图片描述

在这里插入图片描述
参考 若依 配置:

'use strict'
const path = require('path')

function resolve(dir) {
    
    
  return path.join(__dirname, dir)
}

const CompressionPlugin = require('compression-webpack-plugin')

const name = process.env.VUE_APP_TITLE || '若依管理系统' // 网页标题

const port = process.env.port || process.env.npm_config_port || 80 // 端口

// vue.config.js 配置说明
//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions
// 这里只列一部分,具体配置参考文档
module.exports = {
    
    
  // 部署生产环境和开发环境下的URL。
  // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上
  // 例如 https://www.ruoyi.vip/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.ruoyi.vip/admin/,则设置 baseUrl 为 /admin/。
  publicPath: process.env.NODE_ENV === "production" ? "/" : "/",
  // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist)
  outputDir: 'dist',
  // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下)
  assetsDir: 'static',
  // 是否开启eslint保存检测,有效值:ture | false | 'error'
  lintOnSave: process.env.NODE_ENV === 'development',
  // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
  productionSourceMap: false,
  // webpack-dev-server 相关配置
  devServer: {
    
    
    host: '0.0.0.0',
    port: port,
    open: true,
    proxy: {
    
    
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      [process.env.VUE_APP_BASE_API]: {
    
    
        target: `http://localhost:8080`,
        changeOrigin: true,
        pathRewrite: {
    
    
          ['^' + process.env.VUE_APP_BASE_API]: ''
        }
      }
    },
    disableHostCheck: true
  },
  css: {
    
    
    loaderOptions: {
    
    
      sass: {
    
    
        sassOptions: {
    
     outputStyle: "expanded" }
      }
    }
  },
  configureWebpack: {
    
    
    name: name,
    resolve: {
    
    
      alias: {
    
    
        '@': resolve('src')
      }
    },
    plugins: [
      // http://doc.ruoyi.vip/ruoyi-vue/other/faq.html#使用gzip解压缩静态文件
      new CompressionPlugin({
    
    
        cache: false,                   // 不启用文件缓存
        test: /\.(js|css|html)?$/i,     // 压缩文件格式
        filename: '[path].gz[query]',   // 压缩后的文件名
        algorithm: 'gzip',              // 使用gzip压缩
        minRatio: 0.8                   // 压缩率小于1才会压缩
      })
    ],
  },
  chainWebpack(config) {
    
    
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
    
    
        symbolId: 'icon-[name]'
      })
      .end()

    config.when(process.env.NODE_ENV !== 'development', config => {
    
    
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
    
    
            // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()

          config.optimization.splitChunks({
    
    
            chunks: 'all',
            cacheGroups: {
    
    
              libs: {
    
    
                name: 'chunk-libs',
                test: /[\\/]node_modules[\\/]/,
                priority: 10,
                chunks: 'initial' // only package third parties that are initially dependent
              },
              elementUI: {
    
    
                name: 'chunk-elementUI', // split elementUI into a single package
                test: /[\\/]node_modules[\\/]_?element-ui(.*)/, // in order to adapt to cnpm
                priority: 20 // the weight needs to be larger than libs and app or it will be packaged into libs or app
              },
              commons: {
    
    
                name: 'chunk-commons',
                test: resolve('src/components'), // can customize your rules
                minChunks: 3, //  minimum common number
                priority: 5,
                reuseExistingChunk: true
              }
            }
          })

          config.optimization.runtimeChunk('single'),
          {
    
    
             from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件
             to: './' //到根目录下
          }
    })
  }
}

执行 npm run build 即可。

二、Nginx配置gzip

worker_processes  1;

events {
    
    
    worker_connections  1024;
}

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

    server {
    
    
        listen       80;
        server_name  localhost;
		charset utf-8;
		# ---------------------------------------------------------------------------
		# 开启gzip压缩
		gzip on;
		# 不压缩临界值,大于1K的才压缩,一般不用改
		gzip_min_length 1k;
		# 压缩缓冲区
		gzip_buffers 16 64K;
		# 压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
		gzip_http_version 1.1;
		# 压缩级别,1-10,数字越大压缩的越好,时间也越长
		gzip_comp_level 5;
		# 进行压缩的文件类型
		gzip_types text/plain application/x-javascript text/css application/xml application/javascript;
		# 跟Squid等缓存服务有关,on的话会在Header里增加"Vary: Accept-Encoding"
		gzip_vary on;
		# IE6对Gzip不怎么友好,不给它Gzip了
		gzip_disable "MSIE [1-6]\.";
		# ---------------------------------------------------------------------------
		
		location / {
    
    
            root   /home/ruoyi/projects/ruoyi-ui;
			try_files $uri $uri/ /index.html;
            index  index.html index.htm;
        }
		
		location /prod-api/ {
    
    
			proxy_set_header Host $http_host;
			proxy_set_header X-Real-IP $remote_addr;
			proxy_set_header REMOTE-HOST $remote_addr;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_pass http://localhost:8080/;
		}

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
    
    
            root   html;
        }
    }
}

使用Gzip解压缩静态文件

需要先完成上述的步骤 环境部署-Nginx配置-开启Gzip压缩

上述方案配置后由于Nginx的动态压缩是对每个请求先压缩再输出,这样造成虚拟机浪费了很多CPU。解决这个问题可以利用nginxhttp_gzip_static_module模块,主要作用是对于需要压缩的文件,直接读取已经压缩好的文件(文件名为加.gz),而不是动态压缩(消耗性能)。所以采用这个方案需要确保目录文件名有生成.gz(最新版本的配置打包默认都会生成.gz文件)

首先需要安装nginxhttp_gzip_static_module模块

安装模块(如果存在其他模块,用空格分开 --with-xxx --with-xxx,防止覆盖)

./configure --with-http_gzip_static_module

编译

make & make install
查询安装配置信息是否包含http_gzip_static_module

./nginx -V

nginx version: nginx/1.8.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --with-http_ssl_module --with-http_gzip_static_module

配置nginx.confgzip_static属性

server {
    
    
	listen       80;
	server_name vue.ruoyi.vip;
	# 开启解压缩静态文件
	gzip_static on;
	location / {
    
    
		root   /home/ruoyi/projects/ruoyi-ui;
		try_files $uri $uri/ /index.html;
		index index.html;
	}
}

开启gzip_static后,对于任何文件都会先查找是否有对应的gz文件。

重启nginx,使其生效

./nginx -s reload

测试解压缩静态文件是否成功

查询 nginx worker 进程的PID

ps ax | grep nginx

使用strace追踪是否请求.gz

# 注意 23558  是 work 线程的id
strace -p 23558 2>&1 | grep gz

如果请求.gz的文件表示开启成功

open("/xxxx/static/css/chunk-171ca186.f59a1d86.css.gz", O_RDONLY|O_NONBLOCK) = 46
open("/xxxx/static/js/chunk-01ef53b6.a7928e48.js.gz", O_RDONLY|O_NONBLOCK) = 46

参考资料:
http://doc.ruoyi.vip/ruoyi-vue/other/faq.html#%E4%BD%BF%E7%94%A8gzip%E8%A7%A3%E5%8E%8B%E7%BC%A9%E9%9D%99%E6%80%81%E6%96%87%E4%BB%B6
http://doc.ruoyi.vip/ruoyi-vue/document/hjbs.html#nginx%E9%85%8D%E7%BD%AE

猜你喜欢

转载自blog.csdn.net/WSYLH/article/details/131892077