Vue online packaging optimization

Vue online packaging optimization

When developing a Vue project, we usually need to package and optimize the project to provide a higher performance application in the production environment. This blog will introduce some Vue online packaging optimization techniques to help you optimize the loading speed and performance of your application.

1. It is forbidden to generate sourceMap files

During the packaging process of the Vue project, the sourceMap file will be generated by default. The main function of sourceMap is to make the packaged file look like uncompressed code, which is convenient for debugging and locating errors. However, we usually don't need these files in a production environment because they increase the size of the application. You can vue.config.jsconfigure to disable sourceMap file generation in:

// vue.config.js
module.exports = {
  productionSourceMap: false, // 是否在构建生产包时生成sourceMap文件,false将提高构建速度
}

2. Turn off prefetch (Prefetch)

Vue CLI 3 enables the prefetch function by default, that is, to prefetch the content that the user may visit in the future when the first screen is loaded. This may cause some unnecessary traffic consumption. If your project has traffic restrictions, consider turning off the prefetch function. In vue.config.jsset as follows:

// vue.config.js
module.exports = {
  chainWebpack: config => {
    // 移除prefetch插件
    config.plugins.delete('prefetch')

    // 或者修改它的选项:
    config.plugin('prefetch').tap(options => {
      options[0].fileBlacklist = options[0].fileBlacklist || []
      options[0].fileBlacklist.push(/myasyncRoute(.)+?\.js$/)
      return options
    })
  }
}

3. Routing lazy loading

For some pages, we may want to package all components under it into the same asynchronous chunk (chunk) to reduce the number of requests when the first screen is loaded. You can use a special annotation syntax to provide a chunk name to implement lazy loading of routes:

const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue')

4. Load Element UI components on demand

After the Vue project is packaged, if the complete Element UI component library is used, the volume of the project will increase. In order to reduce the packaged volume, we can introduce Element UI components as needed. In the Vue CLI 3.x version, the configuration file is babel.config.js, which can be configured according to the following steps:

  1. Install the babel plugin:
    npm install babel-plugin-component -D
    

    Configured in babel.config.jsas follows:

    module.exports = {
      presets: [
        '@vue/cli-plugin-babel/preset',
        ["@babel/preset-env", { "modules": false }]
      ],
      "plugins": [
        [
          "component",
          {
            "libraryName": "element-ui",
            "styleLibraryName": "theme-chalk"
          }
        ]
      ]
    }
    

    5. Use CDN to load external resources

    For some commonly used external resources, such as Vue, Vuex, Vue Router, Axios, etc., we can import them through CDN to reduce the packaged file size. The following is vue.config.jsthe core code for configuring CDN loading in:

    const isProduction = process.env.NODE_ENV === 'production';
    const cdn = {
        css: [],
        js: [
            'https://cdn.bootcss.com/vue/2.5.17/vue.runtime.min.js',
            'https://cdn.bootcss.com/vue-router/3.0.1/vue-router.min.js',
            'https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js',
            'https://cdn.bootcss.com/axios/0.18.0/axios.min.js',
        ]
    }
    module.exports = {
        chainWebpack: config => {
            // 生产环境配置
            if (isProduction) {
                // 生产环境注入CDN
                config.plugin('html')
                    .tap(args => {
                        args[0].cdn = cdn;
                        return args;
                    });
            }
        },
        configureWebpack: config => {
            if (isProduction) {
                // 用CDN方式引入
                config.externals = {
                    'vue': 'Vue',
                    'vuex': 'Vuex',
                    'vue-router': 'VueRouter',
                    'axios': 'axios'
                }
            }
        },
    }
    

    In index.html, we can dynamically add the corresponding CSS and JS files according to the configuration of CDN loading external resources.

    6. Use Gzip for compression

    After the packaging is complete, we can further use Gzip to compress the packaged files to reduce the file size. First, install compression-webpack-pluginthe plugin:

    npm install compression-webpack-plugin -D
    

    Then vue.config.jsimport the plugin in and configure compression options:

    const CompressionPlugin = require('compression-webpack-plugin')
    
    configureWebpack: (config) => {
        if (process.env.NODE_ENV === 'production') {
            // 为生产环境修改配置...
            config.mode = 'production'
            return {
                plugins: [new CompressionPlugin({
                    test: /\.js$|\.html$|\.css/, //匹配文件名
                    threshold: 10240, //对超过10k的数据进行压缩
                    deleteOriginalAssets: false //是否删除原文件
                })]
            }
        }
    }
    

    7. Image compression

    For the image resources in the project, you can use image-webpack-loaderthe image compression to reduce the size of the image. First, install image-webpack-loader:

    npm install image-webpack-loader --save-dev
    

    Then chainWebpackadd the following code in:

    config.plugins.delete('prefetch')
    config.module.rule('images')
        .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
        .use('image-webpack-loader')
        .loader('image-webpack-loader')
        .options({ bypassOnDebug: true })
    

    Eight, code compression

    The final step is to minify the code to remove unnecessary code and comments. We can use uglifyjs-webpack-pluginplugins to achieve this. First, install the plugin:

    npm install -D uglifyjs-webpack-plugin
    

    Then configureWebpackadd the following code to it:

    const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
    
    new UglifyJsPlugin({
        uglifyOptions: {
            // 生产环境自动删除console
            compress: {
                drop_debugger: true,
                drop_console: true,
                pure_funcs: ['console.log']
            }
        },
        sourceMap: false,
        parallel: true
    })
    

    The above are some techniques for Vue online packaging optimization. By disabling sourceMap, turning off prefetching, lazy loading of routes, loading Element UI components on demand, loading external resources using CDN, using Gzip compression, image compression and code compression, etc., you can Vue applications run more efficiently and quickly in production environments. According to your actual needs, choose the optimization method suitable for your project to provide better user experience and performance. Source: Station B UP - Programmer's Little Partner

Guess you like

Origin blog.csdn.net/weixin_60895836/article/details/132019782