vue packaging optimizes image compression through image webpack loader plug ins

  • 2021-09-20 19:15:57
  • OfStack

After vue is normally packaged, some picture files are very large, which makes the packaging volume very large. Through image-webpack-loader plug-ins, large pictures can be compressed to reduce the packaging volume

step1:

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

step2:

Change the following configuration in build/webpack. base. conf. js


module.exports = {
 
 module: { 
   {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    // loader: 'url-loader',
    // options: {
     // limit: 100000,
     // name: utils.assetsPath('img/[name].[hash:7].[ext]')
    // }
    loader: ['url-loader?limit=10000&name=' + utils.assetsPath('img/[name].[hash:7].[ext]'),
     'image-webpack-loader'
    ]
   },
 
   
  ]
 },
}

Supplementary Knowledge: Key Points of Packaging and Optimizing Configuration of vuecli3 Project

1. New projects

Build an initial Vue project using vue-cli3

Because cli3 is used, many directory structures are missing, and related configurations are placed in vue. config. js, so create a new vue. config. js in the root directory

module.exports = {}

2. Formal optimization

1. Set productionSourceMap to false

(1) Write module. exports in vue. config. js:


module.exports = {
  productionSourceMap: false
}

2. Picture compression

After vue is normally packaged, some picture files are very large, so that the packaging volume is very large. Through image-webpack-loader plug-ins, large pictures can be compressed to reduce the packaging volume

(1) Install dependencies first: cnpm install image-webpack-loader-save-dev

(2) Write module. exports in vue. config. js:


module.exports = {
  productionSourceMap: false,
  chainWebpack: config => {
    // ============ Compressed picture  start============
    config.module
      .rule('images')
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({ bypassOnDebug: true })
      .end()
    // ============ Compressed picture  end============
  }
}

3. cdn configuration (optional)

(1) At the top of vue. config. js, write:


//  Whether it is 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 window The name of the variable mounted inside) 
  externals: {
    vue: 'Vue',
    vuex: 'Vuex',
    'vue-router': 'VueRouter'
  },
  // cdn Adj. css Link 
  css: [],
  // cdn Adj. js Link 
  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'
  ]
}

(2) Write in vue. config. js module. exports chainWebpack:


// ============ Injection cdn start============
config.plugin('html').tap(args => {
  //  Production environment or local needs cdn Before injecting cdn
  if (isProduction || devNeedCdn) args[0].cdn = cdn
  return args
})
// ============ Injection cdn start============

(3) Write in vue. config. js module. exports configureWebpack:


configureWebpack: config => {
  //  Use cdn Method is introduced, the related resources should be ignored when building 
  if (isProduction || devNeedCdn) config.externals = cdn.externals
}

(4) Currently configured vue. config. js


//  Whether it is 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 window The name of the variable mounted inside) 
  externals: {
    vue: 'Vue',
    vuex: 'Vuex',
    'vue-router': 'VueRouter'
  },
  // cdn Adj. css Link 
  css: [],
  // cdn Adj. js Link 
  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'
  ]
}

module.exports = {
  productionSourceMap: false,
  chainWebpack: config => {
    // ============ Compressed picture  start============
    config.module
      .rule('images')
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({ bypassOnDebug: true })
      .end()
    // ============ Compressed picture  end============

    // ============ Injection cdn start============
    config.plugin('html').tap(args => {
      //  Production environment or local needs cdn Before injecting cdn
      if (isProduction || devNeedCdn) args[0].cdn = cdn
      return args
    })
    // ============ Injection cdn start============
  },
  configureWebpack: config => {
    //  Use cdn Method is introduced, the related resources should be ignored when building 
    if (isProduction || devNeedCdn) config.externals = cdn.externals
  }
}

(5) Write in public index. html


<!DOCTYPE html>
<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.ico" />
    <!--  Use CDN Adj. CSS Documents  -->
    <% for (var i in htmlWebpackPlugin.options.cdn &&
    htmlWebpackPlugin.options.cdn.css) { %>
    <link
      href="<%= htmlWebpackPlugin.options.cdn.css[i] %>"
      rel="stylesheet"
    />
    <% } %>
    <!--  Use CDN Adj. CSS Documents  -->
    <title>cli3_base</title>
  </head>
  <body>
    <noscript>
      <strong
        >We're sorry but cli3_base doesn't work properly without
        JavaScript enabled. Please enable it to continue.</strong
      >
    </noscript>
    <div id="app"></div>

    <!--  Use CDN Adj. JS Documents  -->
    <% for (var i in htmlWebpackPlugin.options.cdn &&
    htmlWebpackPlugin.options.cdn.js) { %>
    <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
    <% } %>
    <!--  Use CDN Adj. JS Documents  -->

    <!-- built files will be auto injected -->
  </body>
</html>

(6) Restart the project npm run serve

(7) Modified in src/router. js

Will

Vue.use(Router)

Replace with

if (!window.VueRouter) Vue.use(Router)

(8) Just restart npm run serve. The current configuration is the development environment, which is invisible in the browser's Network JS. If you want to view it, please check the inside of vue. config. js

//Does the local environment require cdn

const devNeedCdn = false

Replace with

//Does the local environment require cdn

const devNeedCdn = true

Then restart npm run serve again, and then view Network JS in the browser

Network JS

4. Code compression

(1) Installation dependencies: cnpm i-D uglifyjs-webpack-plugin

(2) Introducing dependencies at the top of vue. config. js

//Code compression

const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

(3) Add in vue. config. js module. exports configureWebpack


//  Production environment related configuration 
if (isProduction) {
  //  Code compression 
  config.plugins.push(
    new UglifyJsPlugin({
      uglifyOptions: {
        // Automatic Delete of Production Environment console
        compress: {
          warnings: false, //  If the package is wrong, comment this line 
          drop_debugger: true,
          drop_console: true,
          pure_funcs: ['console.log']
        }
      },
      sourceMap: false,
      parallel: true
    })
  )
}

5. Turn on Gzip

(1) Installation dependencies: cnpm install--save-dev compression-webpack-plugin

(2) Introducing dependencies on top of vue. config. js

//gzip compression

const CompressionWebpackPlugin = require('compression-webpack-plugin')

(3) Add it in vue. config. js module. exports configureWebpack, and put it directly under code compression


//  Production environment related configuration 
if (isProduction) {
  //  Code compression 
  // ..................
  // gzip Compression 
  const productionGzipExtensions = ['html', 'js', 'css']
  config.plugins.push(
    new CompressionWebpackPlugin({
      filename: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' + productionGzipExtensions.join('|') + ')$'
      ),
      threshold: 10240, //  Only resources larger than this value are processed  10240
      minRatio: 0.8, //  Only resources whose compression ratio is less than this value will be processed 
      deleteOriginalAssets: false //  Delete the original file 
    })
  )
}

6. Common code extraction

(1) Add it in vue. config. js module. exports configureWebpack, and place it directly under gzip compression


module.exports = {
  productionSourceMap: false
}
0

Complete vue. config. js


module.exports = {
  productionSourceMap: false
}
1

Related articles: