Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

preface

Blessed by Buddha, there is no bug. Hello everyone! I am across the sea!

As we get used to the project and Vue gets used to it, we want to expand. Performance optimization is a good place to go

Let’s talk about GZIP this time

This time is to test the response, said a data network request is a little slow, let me optimize

To solve the process

1. Look at the scene of the accident

2. Usecompression-webpack-plugin

Install compression will – webpack – the plugin

NPM install --save-dev compression-webpack-plugin or yarn add compression-webpack-plugin -dCopy the code

Ps:

  1. There is also a small pit, installed by defaultcompression-webpack-pluginVersion is^ 7.1.2When used, an error was reportedCannot read property 'tapPromise' of undefined
  2. The solution is to install oneLow versionthecompression-webpack-pluginThrough the thunder of my tread,5.0.1The version of the
NPM uninstall --save-dev compression-webpack-plugin or YARN remove compression-webpack-plugin NPM I --save-dev compression-webpack-plugin@5.01.Or yarn add compression will - webpack - plugin @5.01. -D
Copy the code

3. Configure vue.config.js

// Package using gzip compression
const CompressionWebpackPlugin = require('compression-webpack-plugin');

// Define the compressed file type
const productionGzipExtensions = ['js'.'css'];


module.exports = {
  ...
  configureWebpack: {
    plugins: [
      new CompressionWebpackPlugin({
        filename: '[path].gz[query]'.algorithm: 'gzip'.test: new RegExp('\ \. (' + productionGzipExtensions.join('|') + '$'), // Match the file name

        threshold: 10240.// Compress data over 10K

        minRatio: 0.8./ / minute]}}}),Copy the code

Vue. Config.js complete code:

const path = require("path");
const TerserPlugin = require('terser-webpack-plugin');

// Package using gzip compression
const CompressionWebpackPlugin = require('compression-webpack-plugin');
// Define the compressed file type
const productionGzipExtensions = ['js'.'css'];

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

module.exports = {
  // Run the environment directory after packaging
  publicPath: process.env.NODE_ENV === "production" ? "/GisFrame2/" : "/".lintOnSave: true.// whether eslint-loader checks when saving
  productionSourceMap: false.// Whether the production environment generates the sourceMap file
  filenameHashing: true./ / file hash
  devServer: {
    // port: 3306,
    open: true.proxy: {
      "/api": {
        / / target: http://xxx.xxx.xx.xxx:xxxx/api/ ", / / / development server interface
        / / target: "http://xxx.xxx.xx.xxx:xxxx/api/", / / / test server interface
        target: "http://xxx.xxx.xx.xxx:xxxx/api/".// [formal server interface]
        ws: true.changeOrigin: true.pathRewrite: {
          "^/api": "/" // Path-forwarding proxy}},"/LocalDemoApi": {
        target: "http://localhost:8080".// The path points to the local host address and port number
        ws: true.changeOrigin: true.pathRewrite: {
          "^/LocalDemoApi": "/DemoData" // Path-forwarding proxy}}}},/* Configure vue-cli3 project, which can be said to be all in vue.config.js. Encapsulation, of course, leaves room for the user to customize the underlying operations. The vue.config.js configuration item has two ports, configureWebpack and chainWebpack. ConfigureWebpack: It is the easiest way to adjust webPack configurations. You can add or overwrite configurations in the CLI. It can be an object that is merged into webpack Settings by webpack-merge, or a function that can be modified or added directly if you need to conditionally configure the behavior based on the environment (this function is executed lazily after the environment variables are set). The first parameter to the method receives the parsed configuration. Within a function, you can modify the configuration directly, or return an object that will be merged. ChainWebpack: This library provides an upper-level abstraction of the original webPack configuration, allowing it to define named Loader rules and named plug-ins that can be invoked via a chain of methods provided by the library, which is used in cli-service */
  configureWebpack: {
    plugins: [ 
      new TerserPlugin({
        terserOptions: {
          ecma: undefined.warnings: false.parse: {},
          compress: {
            drop_console: true.drop_debugger: false.pure_funcs: ['console.log'] / / remove the console}}}),new CompressionWebpackPlugin({
        filename: '[path].gz[query]'.algorithm: 'gzip'.test: new RegExp('\ \. (' + productionGzipExtensions.join('|') + '$'), // Match the file name
        threshold: 10240.// Compress data over 10K
        minRatio: 0.8./ / minute})],},chainWebpack: config= > {
    Resolve. Alias is implemented in Webpack. Add and modify the desired alias configuration using the set method
    config.resolve.alias
      .set("@", resolve("src"))
      .set("spatial", resolve("public/SpatialData"))
      .set("assets", resolve("src/assets"))
      .set("components", resolve("src/components")); }};Copy the code

4. Enable gzip performance optimization on the nginx server

Package up the project and take a look

There are a lot of things that can be said about nginx performance optimization, such as the number of nginx running worker processes, Nginx running CPU affinity, nginx maximum number of open files, NGINx event handling model, enabling efficient transfer mode, connection timeout, FastCGI tuning, GZIP tuning, Expires cache tuning, anti-spoofing, kernel parameter optimization, and more

This time we will focus on GZIP tuning

The core configuration code is as follows, I have added comments, can be assured to eat:

gzip on; # gzip on off gzip_disable"msie6"; Gzip IE6 gzip_min_length 100k; #gzip compress the minimum file size, exceeding the compression (self-tuning) gzip_buffers416k; Buffer does not need to change gzip_comp_level8; # compression level:1-10The larger the number, the better the compression. Gzip_types text/plain Application /x-javascript text/ CSS application/ XML text/javascript application/x-httpd-php image/jpeg image/gif image/png; Gzip_static on; # nginx will first match your gzip file to return, if not find the appropriate resource to gzip and returnCopy the code

The complete nginx.conf configuration code is as follows:

HTTP {# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = open nginx server gzip performance optimization = = = = = = = = = = = = = = = = = = = = = = = = = = = = = gzip on; # gzip on off gzip_disable"msie6"; Gzip IE6 gzip_min_length 100k; #gzip compress the minimum file size, exceeding the compression (self-tuning) gzip_buffers416k; Buffer does not need to change gzip_comp_level8; # compression level:1-10The larger the number, the better the compression. Gzip_types text/plain Application /x-javascript text/ CSS application/ XML text/javascript application/x-httpd-php image/jpeg image/gif image/png; Gzip_static on; # nginx will preferentially match your gzip file to return, If not, gzip the resource and return # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = open nginx server gzip performance optimization = = = = = = = = = = = = = = = = = = = = = = = = = = = = = the 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;

    server {
        listen       8081; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; }... }Copy the code

5. See the effect after deployment

Now that you’ve seen this, please give me a thumbs up before you go, because your thumbs up means a lot to me