Vue-cli3.0 daily optimization

Time:2022-7-29

1. Introduction of the project’s third-party library CDN

CDN resources are mainly used to reduce the volume of packaged files

Vue.config.js

//Is it a production environment
const isProduction = process.env.NODE_ENV !== 'development'
//Does the local environment need to use CDN
const devNeedCdn = false

//CDN link
const cdn = {
  //CDN: module name and module scope name (corresponding to the variable name mounted in the window)
  externals: {
    vue: 'Vue',
    // vuex: 'Vuex',
    'vue-router': 'VueRouter',
    axios: 'axios',
    vant: 'vant',
  },
  //CSS link of CDN
  css: [
    'https://cdn.jsdelivr.net/npm/[email protected]/lib/index.css',
  ],
  //JS link of CDN
  js: [
    'https://cdn.staticfile.org/vue/2.6.10/vue.min.js',
    // 'https://cdn.staticfile.org/vuex/3.0.1/vuex.min.js',
    'https://cdn.staticfile.org/vue-router/3.0.3/vue-router.min.js',
    'https://cdn.bootcss.com/axios/0.19.2/axios.min.js',
    'https://cdn.jsdelivr.net/npm/[email protected]/lib/vant.min.js',
    // 'https://cdn.bootcss.com/moment.js/2.24.0/moment.min.js',
    // 'https://cdn.bootcss.com/echarts/3.7.1/echarts.min.js'
  ]
}

module.exports = {
    chainWebpack:config => {
        
      //Configure CDN import
      config.plugin('html').tap(args => {
        args[0].cdn = cdn
        return args
      })
        
    }
    configureWebpack:config => {
    //If it is introduced by CDN, relevant resources should be ignored during construction
    if (isProduction || devNeedCdn) config.externals = cdn.externals
}

pulic / index.html

2. Package each dependent package into a separate js/css file

vue.config.js

module.exports = {
      chainWebpack: config => {
          
        //Package each dependent package into a separate JS file
          let optimization = {
              runtimeChunk: 'single',
              splitChunks: {
                  chunks: 'all',
                  maxInitialRequests: Infinity,
                  Minsize: 20000, // dependent packages with more than 20000bit will be packaged separately
                  cacheGroups: {
                      vendor: {
                          test: /[\\/]node_modules[\\/]/,
                          name (module) {
                              // get the name. E.g. node_modules/packageName/not/this/part.js
                              // or node_modules/packageName
                              const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
                              // npm package names are URL-safe, but some servers don't like @ symbols
                              return `npm.${packageName.replace('@', '')}`
                          }
                      }
                  }
              }
          }
          Object.assign(config, {
              optimization
          })

          Object.assign(config, {
              output:{
                  ...config.output,
                  filename: `js/[name].[chunkhash].${version}.js`,
chunkFilename: `js/[name].[chunkhash].${version}.js`
},
});

3. The project automatically introduces the third-party plug-in style, and removes the use of CDN import style

In babel.config.js

//Style true will automatically introduce the vant CSS style. When packaged, it will be packaged into the CSS style of a third party
//Reference configuration during development    
module.exports = {
  presets: ['@vue/cli-plugin-babel/preset'],
  plugins: [
    [
      'import',
      { libraryName: 'vant', libraryDirectory: 'es', style: false },
      'vant'
    ]
  ]
};

When using CDN to import vant, main JS entry file needs to be transformed

//Remove vant introduction
//import vant from 'vant'

//Lazload components will not be automatically registered when imported through CDN
//You can register manually in the following way
Vue.use(vant.Row);
Vue.use(vant.Col);
Vue.use(vant.Icon);
Vue.use(vant.Cell);

4. Define the abbreviated path of the folder

vue.config.js

const path = require('path')

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

module.exports = {
    
    chainWebpack:config => {
        
         //Define the path of the folder
    	config.resolve.alias
          .set('@', resolve('src'))
          .set('@st', resolve('static'))	
        
    }
}

5. Remove the preload prefetch/preload of the packaged file

vue.config.js

module.exports = {
    chainWebpack:config=>{
        //Production environment development development environment
        if (process.env.NODE_ENV === 'production') {
            //Modify configuration for production environment
            //Remove the prefetch plug-in
            config.plugins.delete("prefetch");
            //Remove the preload plug-in
            config.plugins.delete('preload');
            //Compress code
            config.optimization.minimize(true);
            //Split code
            // config.optimization.splitChunks({
            //   chunks: 'all',
            // })
        }
	}
}

Preload tells the browser that the page must need resources, and the browser will load these resources

Prefetch is to tell the browser the resources that the page may need. The browser does not necessarily load these resources

6. Do not generate the corresponding map file

module.exports = { 
	productionSourceMap: false,
}

//Productionsourcemap controls whether map files are generated in the production environment,
//Devtool is the configuration of development and debugging. If you configure it as source map, this file will be generated. Configure it as false.

If it does not take effect, the map file will still be generated

inspectconfigureWebpackIn configurationdevtooloption

module.exports = { 
    configureWebpack(config){
        config.devtool=config.mode==="production"?false:"source-map";
    }
}

The function of the map file is: after the project is packaged, the code is compressed and encrypted. If an error is reported when running, the output error information cannot accurately know where the code is reporting an error. In other words, the map file is equivalent to checking the source code. If you don’t need to locate the problem and don’t want to be seen the source code, set productionsourcemap to false, which can not only reduce the package size, but also encrypt the source code

Recommended Today

JS generate guid method

JS generate guid method https://blog.csdn.net/Alive_tree/article/details/87942348 Globally unique identification(GUID) is an algorithm generatedBinaryCount Reg128 bitsNumber ofidentifier , GUID is mainly used in networks or systems with multiple nodes and computers. Ideally, any computational geometry computer cluster will not generate two identical guids, and the total number of guids is2^128In theory, it is difficult to make two […]