Vue-cli3.0 packaging optimization practice

  1. Configure gzip compression to print out a file to be gzip suffixed
  2. Webpack – bundle – analyzer analysis
  3. Webpack splitChunks, generic ‘echarts’ extracted, ‘moment’, ‘Element-UI ‘,’ XLSX ‘etc
  4. Momentjs optimization
  5. Lodash optimization
  6. Small images are compressed into Base64 format
  7. XLSX XLSX instead. The mini. Min
  8. Nginx http1.1 changed to HTTP2.0
  9. SEO optimization
  10. Infrequently updated modules are removed (to be updated)

Optimized analysis diagram – address

Comparison before and after optimization

parsed

Size before optimization Size after optimization 2.7MB -> 2.11MBCopy the code





gzip

Size before optimization Size after optimization 882.15KB -> 685.23KBCopy the code





Lighthouse

1. Configure gzip compression to print a file to be suffixed with gzip

$ npm i compression-webpack-plugin -D
Copy the code
const CompressionWebpackPlugin = require('compression-webpack-plugin');
module.exports = {
    configureWebpack: config= > {
        if (process.env.NODE_ENV === 'production') { config.plugins.push( ... [new CompressionWebpackPlugin({
                        filename: '[path].gz[query]'.algorithm: 'gzip'.test: /\.(js|css|html|svg)$/i,
                        threshold: 2048.minRatio: 0.8})]); }}};Copy the code

2. Webpack-bundle-analyzer analysis package

$ npm i webpack-bundle-analyzer -D

Copy the code
module.exports = {
    chainWebpack: config= > {
        if (process.env.NODE_ENV === 'production') {
            / / start to dynamically create an HTML: http://localhost:8888/report.html
            // config.plugin('webpack-bundle-analyzer').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin);
            // Generate a static HTML, report.html
            config.plugin('webpack-report').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, [
                {
                    analyzerMode: 'static'}]); }}};Copy the code

3. Webpack splitChunks, extracted generic ‘echarts’, ‘moment’, ‘Element-UI ‘,’ XLSX ‘etc

// ['echarts', 'moment', 'element-ui', 'xlsx', 'chunk-vendors', 'chunk-common', 'index']
module.exports = {
    pages: {
        index: {
            // ...
            // The blocks contained in this page are contained by default
            // The extracted generic chunk and Vendor chunk.
            chunks: ['echarts'.'moment'.'element-ui'.'xlsx'.'chunk-vendors'.'chunk-common'.'index']},chainWebpack: config= > {
            if (process.env.NODE_ENV === 'production') {
                // Vue-cli3. x+ Default configuration
                // config.optimization.splitChunks({
                // chunks: 'async',
                // minSize: 30000,
                // maxSize: 0,
                // minChunks: 1,
                // maxAsyncRequests: 6,
                // maxInitialRequests: 4,
                // automaticNameDelimiter: '~',
                // cacheGroups: {
                // vendors: {
                // name: 'chunk-vendors',
                // test: /[\\/]node_modules[\\/]/,
                // priority: -10,
                // chunks: 'initial'
                / /},
                // common: {
                // name: 'chunk-common',
                // minChunks: 2,
                // priority: -20,
                // chunks: 'initial',
                // reuseExistingChunk: true
                / /}
                / /}
                // });
                config.optimization.splitChunks({
                    chunks: 'async'.minSize: 1024 * 10./ / 30000,
                    maxSize: 0.minChunks: 1.maxAsyncRequests: 6.maxInitialRequests: 4.automaticNameDelimiter: '~'.cacheGroups: {
                        / / link: https://juejin.cn/post/6844904105555525640
                        echarts: {
                            name: 'echarts'.test: /[\\/]node_modules[\\/]echarts[\\/]/,
                            minSize: 0.minChunks: 1.reuseExistingChunk: true.chunks: 'all'
                        },
                        moment: {
                            name: 'moment'.test: /[\\/]node_modules[\\/]moment[\\/]/,
                            minSize: 0.minChunks: 1.reuseExistingChunk: true.chunks: 'all'
                        },
                        'element-ui': {
                            name: 'element-ui'.test: /[\\/]node_modules[\\/]element-ui[\\/]/,
                            minSize: 0.minChunks: 1.reuseExistingChunk: true.chunks: 'all'
                        },
                        xlsx: {
                            name: 'xlsx'.test: /[\\/]node_modules[\\/]xlsx[\\/]/,
                            minSize: 0.minChunks: 1.reuseExistingChunk: true.chunks: 'all'
                        },

                        vendors: {
                            name: 'chunk-vendors'.test: /[\\/]node_modules[\\/]/,
                            priority: -10.chunks: 'initial'
                        },
                        common: {
                            name: 'chunk-common'.minChunks: 2.priority: -20.chunks: 'initial'.reuseExistingChunk: true}}}); }}}}Copy the code

4. Momentjs optimization

  • Option 1: Package only the files you use (the current one)

vue.config.js

module.exports = {
    configureWebpack: config= >{ config.plugins.push( ... [/ / link: https://juejin.cn/post/6844904105555525640
                new webpack.ContextReplacementPlugin(
                    /moment[/\\]locale$/.// This parameter indicates the packaging context we want to change
                    /zh-cn/ // This parameter indicates that we only want to package the regex matching file)]); }};Copy the code
  • Plan 2: Use dayjs instead of moment. The code stays the same. Alias the loDash configuration to dayjs

Article: on zhihu zhuanlan.zhihu.com/p/61031739?…

module.exports = {
    chainWebpack: config= > {
        config.resolve.alias
        // set The first argument: the alias for the setting, the second argument: the real name (both are read from node_modules by default)
        .set('moment'.'dayjs')); }}; - plan3:...Copy the code

5. Lodash optimization

$ npm i lodash-webpack-plugin babel-plugin-lodash -D
Copy the code

babel.config.js

module.exports = {
    presets: ['@vue/app'].plugins: [
        'lodash'['component',
            {
                libraryName: 'element-ui'.styleLibraryName: 'theme-chalk'}}]].Copy the code

vue.config.js

const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

module.exports = {
    configureWebpack: config= >{ config.plugins.push( ... [new LodashModuleReplacementPlugin(),
                / / link: https://juejin.cn/post/6844904105555525640
                new webpack.ContextReplacementPlugin(
                    /moment[/\\]locale$/.// This parameter indicates the packaging context we want to change
                    /zh-cn/ // This parameter indicates that we only want to package the regex matching file)]); }};Copy the code

6. Compress small images into Base64 format

module.exports = {
    chainWebpack: config= > {
        // Images up to 10KB are packed as inline elements
        config.module
            .rule('images')
            .use('url-loader')
            .loader('url-loader')
            .tap(options= > Object.assign(options, {limit: 10240})); }};Copy the code

7. Change XLSX to xlsx.mini

Put all the

import XLSX from 'xlsx';
Copy the code

Change to the following way to introduce

import XLSX from 'xlsx/dist/xlsx.mini.min.js';
Copy the code

8. Upgrade HTTP1.1 to Http2.0

Points to note:

2. The current configuration of HTTP2 is based on HTTPSCopy the code

Nginx configuration file nginx.conf

Listen 80; server_name yourdomain.com; You need to replace yourdomain.com with the domain name bound to the certificate. rewrite ^(.*) https://$server_name$1 permanent; Redirect all HTTP requests to HTTPS using the rewrite directive. } # Of the following properties, the properties that begin with SSL represent the certificate configuration. Server {# enable gzip gzip on; Gzip_min_length 1k will not be compressed for files smaller than the set value. Gzip_comp_level 9; gzip_level 9; gzip_level 9; The type of file to compress. Javascript comes in many forms. The values can be found in the mime.types file. gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png application/vnd.ms-fontobject font/ttf font/opentype font/x-woff image/svg+xml; Gzip_vary on is recommended for HTTP header Vary: accept-encoding. Gzip gzip_disable "MSIE [1-6]\." Gzip_buffers 32 4k; Gzip_http_version 1.1; Http2 listen 443 SSL http2; Set HTTPS to port 443. Nginx may fail to start if the default HTTPS access port is not configured here. If you are using Nginx 1.15.0 or later, use Listen 443 SSL instead of Listen 443 and SSL on. server_name yourdomain.com; You need to replace yourdomain.com with the domain name bound to the certificate. root html; index index.html index.htm; ssl_certificate cert/cert-file-name.pem; Cert-file-name. pem needs to be replaced with the name of the uploaded certificate file. ssl_certificate_key cert/cert-file-name.com.key; # replace cert-file-name.key with the name of the uploaded certificate key file. ssl_session_timeout 5m; ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:! NULL:! aNULL:! MD5:! ADH:! RC4; # indicates the type of cipher suite used. Ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # indicates the type of TLS protocol used. ssl_prefer_server_ciphers on; # location / { # root html; # site directory. # index index.html index.htm; #} location / {# reverse proxy 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 { } }Copy the code

Http2.0 network effect

9. SEO optimization

<meta name="description" content="Vue, Element-UI, NodeJS, Express, Nginx Full stack Management background Project" />

Copy the code

10. Modules not updated frequently are removed (to be updated)

To be updated