vue.config.js packaging optimization configuration

vue.config.js packaging optimization configuration

The information on Baidu is so diverse that it's dizzying. Don't worry, I've experienced it for you. You can refer to it if you need it. I'll post the effect picture first, so that you don't think I'm bragging, hehe

Optimization direction
1. Image resource compression
2. Set productionSourceMap to false, and the map will not be generated
3. CDN configuration (optional)
4. Code compression
5. Extraction of common code (personally I feel it is useless)

Before optimization // It feels too big to lift it

Results before optimization

After optimization

After optimization

Enough nonsense, the code is the key point. These are the necessary downloads.
/*cnpm install image-webpack-loader --save-dev
cnpm install compression-webpack-plugin --save-dev
cnpm install uglifyjs-webpack-plugin --save-dev */

const path = require('path');
// gzip compression const CompressionPlugin = require('compression-webpack-plugin')
//Monitoring log const SentryCliPlugin = require('@sentry/webpack-plugin');
// Code compression const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const Version = new Date().getTime();
function resolve(dir) {
  return path.join(__dirname, dir)
}
const cdn = {
  js: [
    // vue must be in the first 'https://cdn.bootcss.com/vue/2.6.10/vue.min.js',
    'https://cdn.bootcss.com/vuex/3.1.0/vuex.min.js',
    'https://cdn.bootcss.com/vue-router/3.0.6/vue-router.min.js',
    'https://cdn.bootcss.com/axios/0.18.1/axios.min.js',
    'https://cdn.bootcss.com/qs/6.5.1/qs.min.js',
    'https://cdn.jsdelivr.net/npm/[email protected]/lib/vant.min.js'
  ]
}
module.exports = {
  //Base URL when deploying the application package
  publicPath: './',

  //Directory of the production environment build files generated when running vue-cli-service build outputDir: 'wx_vue',

  //Place the generated static resources (js, css, img, fonts) in the directory (relative to outputDir) assetsDir: './' + Version + '/assets',

  // Whether eslint-loader checks the installation of @vue/cli-plugin-eslint when saving lintOnSave: false,

  //Whether to use a Vue build that includes a runtime compiler. After setting true, you can use template
  runtimeCompiler: true,

  //Whether to generate sourceMap file in production environment For details of sourceMap, please see the end productionSourceMap: false,

  /** Remove hash */
  filenameHashing: true,


  // pages: {
  // index: {
  // entry: 'src/main.js',
  // template: 'public/index.html',
  // filename: 'index.html'
  // }
  // },
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      // Modify config for production environment...
      config.mode = 'production'
      config.devtool = "source-map";
    } else {
      // Modify configuration for development environment...
      config.mode = 'development'
    }
    /** Delete prefetch preload of lazy loading module to reduce bandwidth pressure (used on mobile terminals) */
    config.plugins.delete("prefetch").delete("preload")
    config.optimization.minimize(true)
    // gzip compression // config.plugin("compressionPlugin").use(CompressionPlugin).tap(() => [
    // {
    // filename: '[path].gz[query]',
    // algorithm: 'gzip',
    // test: /\.js$|\.html$|\.css/, //Match file name// threshold: 10240, //Compress if the file size is over 10k// minRatio: 0.8, //Only resources with a compression ratio lower than this value will be processed// deleteOriginalAssets: false //Whether to delete the source file// }
    // ])
    config.plugins.push(
      new CompressionPlugin({
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.js$|\.html$|\.css/,
        threshold: 10240, // Only resources larger than this value will be processed 10240
        minRatio: 0.8, // Only resources with a compression ratio lower than this value will be processed deleteOriginalAssets: false // Delete the original file })
    )
    // Common code extraction config.optimization = {
      splitChunks: {
        cacheGroups:
          vendor:
            chunks: 'all',
            test: /node_modules/,
            name: 'vendor',
            minChunks: 1,
            maxInitialRequests: 5,
            minSize: 0,
            priority: 100
          },
          common:
            chunks: 'all',
            test: /[\\/]src[\\/]js[\\/]/,
            name: 'common',
            minChunks: 2,
            maxInitialRequests: 5,
            minSize: 0,
            priority: 60
          },
          styles: {
            name: 'styles',
            test: /\.(sa|sc|c)ss$/,
            chunks: 'all',
            enforce: true
          },
          runtimeChunk: {
            name: 'manifest'
          }
        }
      }
    }
  },
  configureWebpack: {
    resolve: {
      alias: {
        'vue$': 'vue/dist/vue.esm.js',
        '@': resolve('src'),
        '@c': path.resolve(__dirname, './src/components'),
        'assets': path.resolve(__dirname, '../src/assets')
      }
    },
    externals: {
      'vue': 'Vue',
      'vuex': 'Vuex',
      'vue-router': 'VueRouter',
      'axios': 'axios',
      'qs': 'Qs',
      'vant': 'Vant'
      // 'weixin-js-sdk': 'weixin-js-sdk',
      // 'clipboard': 'clipboard',
      // 'qrcodejs2':'qrcodejs2',
      // 'js-md5':'js-md5'
    },
    optimization:
      minimizer:
        new UglifyJsPlugin({
          uglifyOptions: {
            output: { // delete comments comments: false
            },
            //The production environment automatically deletes the console
            compress: {
              //warnings: false, // If the packaging is wrong, comment this line drop_debugger: true, // Clear debugger statement drop_console: true, // Clear console statement pure_funcs: ['console.log']
            }
          },
          sourceMap: false,
          parallel: true
        })
      ]
    }
  },

  // css related configuration css: {
    extract: false,
    loaderOptions: {
      stylus:
        'resolve url': true,
        'import': []
      },
      // less: {
      // // `globalVars` defines a global object, where global variables can be added // globalVars: {
      // primary: '#333'
      // }
      // }
    },
    requireModuleExtension: true,
  },

  // webpack-dev-server related configuration devServer: { // Set proxy hot: true, //Hot loading host: 'localhost', //IP address port: 8085, //Port https: false, //false turns off https, true turns it on open: true, //Automatically open the browser proxy: { //Configure multiple cross-domain '/api': { //Local//target: 'http://172.168.10.150:81/ysol_wx',
        //target: 'http://yishanonline.cn/ysol_wx',
        target: 'https://yishanol.cn/ysol_wx',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  },

  pluginOptions: { // Third-party plugin configuration // ...
  },
  chainWebpack: config => {
    // ============Compress the picturestart============
    config.module
      .rule('images')
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({
        //{ bypassOnDebug: true }
        mozjpeg: { progressive: true, quality: 65 }, Compress JPEG images
        optipng: { enabled: false }, // Compress PNG images
        pngquant: { quality: [0.65, 0.9], speed: 4 }, // Compress PNG images
        gifsicle: { interlaced: false }, // Compress SVG images
        // webp: { quality: 75 }
      })
      .end()
    // config.module.rules.push({
    // test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    // use:[{
    // loader: 'image-webpack-loader',
    // options: {bypassOnDebug: true}
    // }]
    // })
    // ============Compress the pictureend============
    config.plugin('html').tap(args => {
      args[0].cdn = cdn
      return args
    })

    /* Add analysis tools */
    if (process.env.NODE_ENV === 'production') {
      if (process.env.npm_config_report) {
        config
          .plugin('webpack-bundle-analyzer')
          .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
          .end();
        config.plugins.delete('prefetch')
      }
    }

    if (process.env.UMI_ENV === 'production') { //Sourcemap is uploaded only when it is prod. If it is not determined, it will also be uploaded when the project is running. This is not needed for online log output and can be deleted. config.plugin("sentry").use(SentryCliPlugin, [{
        ignore: ['node_modules'],
        include: /\.map$/, //Upload dist file js
        configFile: 'sentry.properties', //Configuration file address, this must be there, stepping on the pit here, forgetting to write it, resulting in the inability to upload sourcemap
        release: '[email protected]', //version number, self-defined variable, the entire version number must correspond in the project deleteAfterCompile: true,
        urlPrefix: '~/wx_vue/' //cdn js code path prefix}])
    }
  }
}

Compared with vue2, vue3 vue.config.js is more concise. You have to configure what you need by yourself to increase your hands-on ability. Except for some grammatical changes, some writing methods are still similar! There is still a long way to go for packaging optimization, I will continue to update next time

This is the end of this article about vue.config.js packaging optimization configuration. For more relevant vue.config.js packaging optimization content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of customizing the packaging path of css, js and pictures in vue-cli3.0
  • Release BlueShow v1.0 Image browser (similar to lightbox) blueshow.js package download
  • Usage and difference of Js module packaging exports require import
  • Teach you step by step how to compile and package video.js
  • nuxt.js adds environment variables to distinguish project packaging environment operations
  • vue solves the problem of uglifyjs-webpack-plugin packaging error
  • Summary of methods for compressing the volume of Vue.js after packaging (Vue.js is too large after packaging)
  • Solve the problem of vendor.js file being too large after vue packaging
  • js realizes packaging multiple pictures into zip

<<:  Example explanation of alarm function in Linux

>>:  Installation and uninstallation of MySQL 5.7 decompressed version and summary of common problems

Recommend

HTML table tag tutorial (19): row tag

The attributes of the <TR> tag are used to ...

Comparing the performance of int, char, and varchar in MySQL

There are many seemingly true "rumors" ...

Example of cross-database query in MySQL

Preface In MySQL, cross-database queries are main...

How to create a basic image of the Python runtime environment using Docker

1. Preparation 1.1 Download the Python installati...

mysql trigger creation and usage examples

Table of contents What is a trigger Create a trig...

Use CSS content attr to achieve mouse hover prompt (tooltip) effect

Why do we achieve this effect? ​​In fact, this ef...

Linux C log output code template sample code

Preface This article mainly introduces the releva...

Seven Principles of a Skilled Designer (1): Font Design

Well, you may be a design guru, or maybe that'...

Essential skills for designing web front-end interfaces

[Required] UserInterface PhotoShop/Fireworks Desi...

TypeScript generic parameter default types and new strict compilation option

Table of contents Overview Create a type definiti...

Vue gets token to implement token login sample code

The idea of ​​using token for login verification ...