Vue-cli3 package volume optimization scheme


Preface:

After the company project is completed, 1.18MB of package is completed, which actually feels fine, but there is still room for optimization. In the spirit of trying to optimize, we can install Webpack-bundle-Analyzer in the project first, so that we can see the size of each file

npm install webpack-bundle-analyzer -save-dev

Copy the code
Configure it in vue.config.js
module.exports = {

    chainWebpackconfig= > {

        config

        .plugin('webpack-bundle-analyzer')

        .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)

    }

}

Copy the code

Running NPM run build or NPM Run serve brings up this fancy interface for analyzing file sizes

Analysis of the

Vendor-app.xxxx. js is 1.18MB before optimization, so we can check the size of each bundle and optimize accordingly

To optimize the

  • CDN load

    Vue, VUE-Router, VUex and AXIos can all be loaded with CDN in the production environment

    const externals = {

      'vue''Vue'.

      'vue-router''VueRouter'.

      'vuex''Vuex'.

      'axios''axios'

    }

    const cdn = {

      css: [].

      js: [

        'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js'.

        'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-router.min.js'.

        'https://cdn.jsdelivr.net/npm/[email protected]/dist/vuex.min.js'.

       'https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js'.

      ]

    }



    module.exports = {

      chainWebpackconfig= > {

          config

          .plugin('webpack-bundle-analyzer')

          .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)

          config.plugin('html').tap(args= > {

          if (process.env.NODE_ENV === 'production') {

            args[0].cdn = cdn

          }

          return args

        })

      },

    configureWebpackconfig= > {

        if (process.env.NODE_ENV === 'production') {

            return {

              externals: externals,

            };

         }

      },

    }

    Copy the code

    Then modify the pubilc/index.html file

    
             

    <html lang="en">

    <head>

      <meta charset="utf-8">

      <meta http-equiv="X-UA-Compatible" content="IE=edge">

      <meta name="viewport" content="Width = device - width, initial - scale = 1.0">

      <link rel="icon" href="<%= BASE_URL %>favicon.png">

      <! CSS file with CDN -->

      <% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.css) { %>

      <link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="external nofollow" rel="external nofollow" rel="preload" as="style">

      <link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="external nofollow" rel="external nofollow" rel="stylesheet">

      <%} % >

      <! -- use CDN JS file -->

      <% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %>

        <link href="<%= htmlWebpackPlugin.options.cdn.js[i] %>" rel="external nofollow" rel="preload" as="script">

      <%} % >

      <title>Shanghai than households</title>

    </head>

    <body>

      <noscript>

        <strong></strong>

      </noscript>

      <div id="app"></div>

      <% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %>

        <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>

      <%} % >

    </body>

    </html>

    Copy the code

    Look at the picture, it is already more than 700 K, which is directly reduced by more than 400 K

  • Route lazy loading

    When packaging applications, JavaScript packages can become very large, affecting page loading. If we load this module when accessing routes, it will become very efficient, changing the static import mode to the dynamic import mode

    import ComponentA from '.. /page/components/ComponentA';

    routeList = [

        {

          path'/comA'.

          component: ComponentA

        },

    ]



    / / to

    routeList = [

        {

          path'/comA'.

          component(a)= > import('.. /page/components/ComponentA')

        },

    ]

    Copy the code

    Since my project started with routing lazy loading, I can’t see the size change in the package file, but there will be about 300K size reduction

    In Vue CLI3, we also need to manually remove prefetch and Preload, because it is mentioned in the official Vue CLI documentation, you can go to see, I have a general overview

    When the first screen is loaded, all the routing files will be downloaded at one time. As a result, there will be more requests for the first screen and the first screen load will be slow. The modification is as follows

    module.exports = {

      chainWebpackconfig= > {

          config

          .plugin('webpack-bundle-analyzer')

          .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)

           config.plugin('html').tap(args= > {

           if (process.env.NODE_ENV === 'production') {

              args[0].cdn = cdn

           }

           return args

         })

          // Remove the prefetch plugin

          config.plugins.delete('prefetch')

          // Remove the preload plugin

          config.plugins.delete('preload');

      },

      configureWebpackconfig= > {

          if (process.env.NODE_ENV === 'production') {

             return {

               externals: externals,

             };

          }

      },

    }

    Copy the code
  • Element-ui loads on demand

    So if you load element-UI on demand, you can reduce the size of the package. If you load element-ui on demand, you can reduce the size of the package

    But it needs to be added in the babel.config.js file (vue cli3 requires babel-plugin-component)

    module.exports = {

        presets: ['@vue/app'].



       // Add this ~

       plugins: [

          [

            'component'.

            {

              libraryName'element-ui'.

              styleLibraryName'theme-chalk'

            }

          ]

       ]

    };

    Copy the code
  • gzip

    Install compression will – webpack – the plugin

    nmp i compression-webpack-plugin -D

    Copy the code

    Introduced in vue.config.js

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



    module.exports = {

        chainWebpackconfig= > {

            config

            .plugin('webpack-bundle-analyzer')

            .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)

             config.plugin('html').tap(args= > {

               if (process.env.NODE_ENV === 'production') {

                 args[0].cdn = cdn

               }

               return args

            })

            // Remove the prefetch plugin

            config.plugins.delete('prefetch')

            // Remove the preload plugin

            config.plugins.delete('preload');

          },

          configureWebpackconfig= > {

            if (process.env.NODE_ENV === 'production') {

              return {

                externals: externals,

                plugins: [

                  / / gzip compression

                  new CompressionPlugin({

                    test/\.js¨E92E.html|\.html¨E92E.html|.\css/.// Match the file name

                    threshold: 10240.// Compress data over 10K

                    deleteOriginalAssets: false // Do not delete the source file

                  })

    ].

                performance: {

                  hintsfalse

                }

              };

           }

        },

    }

    Copy the code

    As you can see in the figure above, the maximum size of the gzip compressed file is only 140K

    But it needs to be configured on the server side

  • SCSS file import

    We usually extract SCSS files, some common styles, themes and so on, and then introduce them into each required component, which will be tedious. We can use SCSS-Loader to preprocess

    For example, we have the resettable. SCSS file, which can be imported in vue. Config.js

    module.exports = {

        chainWebpackconfig= > {

           config

           .plugin('webpack-bundle-analyzer')

           .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)

           config.plugin('html').tap(args= > {

             if (process.env.NODE_ENV === 'production') {

                args[0].cdn = cdn

              }

              return args

            })

            // Remove the prefetch plugin

            config.plugins.delete('prefetch')

            // Remove the preload plugin

            config.plugins.delete('preload');

          },

        configureWebpackconfig= > {

           if (process.env.NODE_ENV === 'production') {

             return {

               externals: externals,

               plugins: [

                 / / gzip compression

                 new CompressionPlugin({

                   test/\.js¨E92E.html|\.html¨E92E.html|.\css/.// Match the file name

                   threshold: 10240.// Compress data over 10K

                   deleteOriginalAssets: false // Do not delete the source file

                 })

    ].

               performance: {

                 hintsfalse

               }

            };

          }

       },

       / / SCSS Settings

       css: {

         loaderOptions: {

           sass: {

             // I put it in assets/commcss

             data: '@import "@assets/commcss/resetTable.scss"; '

           }

         },

       },

    }

    Copy the code

    This is the complete vue.config.js configuration

Conclusion:

These are the points I have optimized in the project so far, but there are certainly other areas that I can discuss

To the wind to embrace the rainbow brave forward ~ 😬