Vue-cli3 scaffold 3’s webpack optimized compression

Time:2021-9-21

Vue-cli3 scaffold 3’s webpack optimized compression

There are a lot of Web pack optimization on the Internet, but many are aimed at bable6 or vue-cli2 or webpack 2.0.

current version
vue-cli3
bable7
webpack4.0

1. Optimize routing

Lazy loading is adopted for routing
example

{
      path: '/loginMode',
      name: 'loginMode',
      component: () => import( /* webpackChunkName: "about" */ './pages/Login/loginMode/loginMode.vue'),
      meta: {
        isTimer: true,
        Title: 'please select login method',
      }
    },

2. The third-party library is loaded on demand

For example, the element UI is loaded on demand in vue-cli3
With the help ofbabel-plugin-component, we can only introduce the required components to reduce the project volume.
First install the Babel plugin component

yarn add babel-plugin-component

Modify babel.config.js

module.exports = {
  plugins: [
    [
      'component',
      {
          libraryName: 'element-ui',
          styleLibraryName: 'theme-chalk'
      }
    ]
  ]
}

Next, if you only want to introduce some componentsVue-cli3 scaffold 3's webpack optimized compression
Introduce the components you need in element-ui.js

import Vue from 'vue'; 
import { Button, Select } from 'element-ui'; 

Vue.use(Button)
Vue.use(Select) 

In this way, the element UI is loaded on demand

3. Gzip compression

If the nginx server starts gzip, the static resources will be compressed on the server. After the compressed package is transmitted to the browser, the browser will decompress and use it, which greatly improves the efficiency of network transmission, especially for text compression such as JS and CSS.

The following is the configuration of enabling gzip by nginx:

#Open | close gzip.
gzip on|off;

#The file is compressed only when it is larger than the specified size, in KB.
gzip_min_length 10;

#The compression level is 1-9. The larger the value is, the larger the compression ratio is, but it takes more CPU, and the compression efficiency is lower and lower.
gzip_comp_level 2;

#Compressed file type.
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript;

#If the. GZ file can be found after opening, the file will be returned directly, and the server compression will not be enabled.
gzip_static on|off
    
#Whether to add a response header. Vary: accept encoding is recommended to be enabled.
gzip_vary on;

#The number and size of buffers requested to be compressed, in 4K units and 32 multiples.
gzip_buffers 32 4K;

If nginx does not enable gzip, the front end can package a compressed version of resources when packaging, and nginx will also transfer the compressed file to the browser

First install a plug-in

yarn add compression-webpack-plugin

Next, configure the plug-in in vue.config.js as follows

//Basic configuration of vue.config.js
const CompressionPlugin = require('compression-webpack-plugin')

module.exports = {
  //The base URL of the application package that will be deployed (baseurl was called before Vue cli 3.3)
  publicPath: "./",
  outputDir: "dist",
  Assetsdir: "assets", // static resource directory (JS, CSS, IMG, fonts)
  Productionsourcemap: false, // the production environment sourcemap does not generate a map file
  Lintonsave: false, // close eslint
  devServer: {
    open: true,
  },
  configureWebpack: config => {
    If (process. Env. Node_env = = = 'production') {// judge the production environment
      return{
        plugins: [
          new CompressionPlugin({
            Algorithm: 'gzip', // enable gzip
            Test: / \. JS $| \. HTML $|. \ CSS /, // match the file name
            Threshold: 10240, // compress data exceeding 10K
            Deleteoriginalassets: false // do not delete the source file
          })
        ]
    }
  }
}

}

4. Do not generate map file

The map file is not required in the production environment, but can be retained in the development environment. Just add productionsourcemap: false in the vue.config.js file
Vue-cli3 scaffold 3's webpack optimized compression

5. Picture compression

Using plug-insimage-webpack-loader
It is best to use cnpm installation, otherwise it is easy to get stuck
cnpm install --save-dev image-webpack-loader
Configure the following in the vue.config.js object

   chainWebpack: config => {
      config.module
          .rule('images')
          .use('image-webpack-loader')
          .loader('image-webpack-loader')
          .options({ bypassOnDebug: true })
          .end()
  }

(attached) optimizing moment.js

useIgnorePluginplug-in unit
The configuration is as follows

const webpack = require('webpack') 
configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      return{
        plugins: [
          New webpack. Ignoreplugin (/ ^ \. \ / locale $/, / moment $/), // ignore all files under / moment / locale
        ]
    }
  }
}

(attached) optimized lodash

uselodash-webpack-pluginplug-in unit

yarn add lodash-webpack-plugin
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')
configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      return{
        plugins: [
            New lodashmodulereplacementplugin(), // optimize lodash
        ]
    }
  }
}

(attached) complete vue.config.js file

//Basic configuration of vue.config.js
const moment = require('moment')
const CompressionPlugin = require('compression-webpack-plugin')
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')
const webpack = require('webpack') 
process.env.VUE_APP_VERSION =  `${moment().format('YYYY.MM.DD')}.${moment().valueOf()}`

module.exports = {
  //The base URL of the application package that will be deployed (baseurl was called before Vue cli 3.3)
  publicPath: "./",
  outputDir: "dist",
  Assetsdir: "assets", // static resource directory (JS, CSS, IMG, fonts)
  Productionsourcemap: false, // production environment sourcemap
  Lintonsave: false, // close eslint
  devServer: {
    open: true,
  },
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      return{
        plugins: [
          new CompressionPlugin({
            Algorithm: 'gzip', // enable gzip
            Test: / \. JS $| \. HTML $|. \ CSS /, // match the file name
            Threshold: 10240, // compress data exceeding 10K
            Deleteoriginalassets: false // do not delete the source file
          }),
          New webpack. Ignoreplugin (/ ^ \. \ / locale $/, / moment $/), // ignore all files under / moment / locale
          New lodashmodulereplacementplugin(), // optimize lodash
        ]
    }
  }
}

}

(attached) complete bable.config.js file

module.exports = {
  presets: [
    '@vue/app'
  ],
  plugins: [
    ['import', {
      libraryName: 'vant',
      libraryDirectory: 'es',
      style: true
    }, 'vant'],
    [
      'component',
      {
          libraryName: 'element-ui',
          styleLibraryName: 'theme-chalk'
      }
  ]
  ]
}

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]