(Webpack Series II) Webpack packaging optimization Exploration

Source: Internet
Author: User
Tags base64 browser cache

Although the Webpack has been upgraded to Webpack4, and we are still using webpack3, the optimization points are the same, and the same applies after the upgrade.

Preliminary principles of performance optimization
    • Reduce the amount of code

    • Reduce the number of requests

    • Maximizing browser cache Usage

These three principles are always the precondition for all optimization.

Optimized configuration
    • Upgrade webpack 3 , optimize JS compiler capability (Scope hoisting)

1// 主要配置
2plugins:[
3  new webpack.optimize.ModuleConcatenationPlugin()
4]
    • Reasonable planning entry of Portal configuration (balance vendor.js, size of app.js file)

 1// main.js中第三方公共库提出,作为公共vendor.js, 配合package.json固定第三方库版本,最大化利用浏览器缓存加载js
2entry: {
3  vendor:[‘vue‘, ‘vue-router‘, ‘vue-resource‘],
4  app: ‘./src/main.js‘
5}
6// ...
7plugins:[
8  new webpack.optimize.CommonsChunkPlugin({
9    name: [‘manifest‘,‘vendor‘].reverse(),
10    minChunks:Infinity
11  })
12]
    • After packaging the file size limit, the first load js+css more than the 400k single file size 300k will be error, package does not pass, the configuration is used in build

1performance: {
2  hints: ‘error‘,
3  maxEntrypointSize: 400000,
4  maxAssetSize: 300000
5}
Reduce the amount of code
    • chunkcommon libraries used in extraction (can save nearly 1/3 of code for chunk code)

1new webpack.optimize.CommonsChunkPlugin({
2  name: ‘app‘,
3  async: ‘vendor-async‘,
4  children: true,
5  minChunks: (module, count) => {
6    // 被 2 个及以上 chunk 使用的共用模块提取出来
7    return count >= 2
8  }
9})
    • Reduce the use of image base64, reduce the limit, limit 2k(Vue official configuration is 10k, will greatly increase the volume of JS file, the mobile end of the resolution of Base64 high cost)

1  {
2    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
3    loader: ‘url-loader‘,
4    options: {
5      limit: 2048,
6      name: utils.assetsPath(‘img/[name].[hash:7].[ext]‘)
7    }
8  }
    • Production mode (PRO) third-party libraries use a compressed version, saving nearly 20k of file size

 1// 开发模式
2resolve: {
3  alias: {
4    ‘vue‘: ‘vue/dist/vue.esm.js‘
5  }
6}
7// 生产模式
8resolve: {
9  alias: {
10    ‘vue‘: ‘vue/dist/vue.min.js‘
11  }
12}
    • Optimized babel-ployfill , combined to babel-preset-env achieve compatible on-demand loading, es2015 saving nearly half the size of use

1entry: {
2  vendor:[‘babel-polyfill‘, ‘vue‘, ‘vue-router‘, ‘axios‘],
3  app: ‘./src/main.js‘
4}
1. BABELRC
2{
3"Presets": [
4 ["Env", {
5       "Modules": false,
6       "targets": {
7         "Browsers": [
8           "> 1%",
9         &NBSP last 3 versions,
          "Firefox ESR ",
          " Not ie < "
       ]
span>13      },
      "Debug": false,
,     and nbsp "Usebuiltins": true
   }],
    "React",
18     "stage-2"
 ]

    • Extreme Compression JS,CSS Code

1var os =Require' OS ')
2var optimizecssplugin =Require' Optimize-css-assets-webpack-plugin ')
3
4plugins: [
5New Webpack.optimize.UglifyJsPlugin ({
6Leverage multi-core capability compression
7 beautify: {
8CacheTrue
9Workers:os.cpus (). length
10},
11The most compact output
Beautify:False
13Delete all comments
Comments:False
15Compress: {
16Do not output a warning when UGLIFYJS deletes unused code
Warnings:False
18Delete all the ' console ' statements
Drop_console:True
      //inline-defined variable
     collapse_vars: true,
span>22       //extract static values that occur multiple times but are not defined as variables to be referenced
%      reduce_vars: true,
   },
    sourcemap: true
 }),
27 & nbsp New Optimizecssplugin ({
      cssprocessor: require ( ' Cssnano ') ({ Span>zindex: false}),
    cssprocessoroptions: {
      Safe: true,
      discardcomments: { removeall: true}
  &NBSP;}
 })

    • The third party libraries relies on filtering, as follows:

1// 此插件默认全部引入语言库,但我们只用到了中文,最多英文,所以进行了过滤,大大减少了总体代码量
2plugins: [
3  new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /zh|en/)
4]
Reduce the number of requests
    • Manifest.js file Inline (App.css can be chosen by itself, when less than 10k is best inline), the Webpack recommended configuration is as follows:

 1// 引入内联插件
2var HtmlWebpackInlineSourcePlugin = require(‘html-webpack-inline-source-plugin‘)
3
4plugins:[
5  // ...
6  new HtmlWebpackPlugin({
7    // ... 其他不相关配置省略
8    inlineSource:/(app\.(.+)?\.css|manifest\.(.+)?\.js)$/,
9    // ...
10  }),
11  new HtmlWebpackInlineSourcePlugin()
12]
Maximizing browser cache Usage

This maximizes the use of browser caching

 1// 不固定版本,会造成打包后 hash 值变化,浏览器没办法利用本身的缓存加载js,每次上线都会使本地缓存失效,页面加载变慢
2"dependencies": {
3  "moment": "2.17.1",
4  "querystring": "0.2.0",
5  "sprite-cli": "0.1.5",
6  "sticky-state": "2.4.1",
7  "superagent-jsonp": "0.1.1",
8  "underscore": "1.8.3",
9  "vue": "2.0.0",
10  "vue-lazyload": "0.8.3",
11  "vue-router": "2.0.0",
12  "vuex": "2.0.0"
13}
Other optimization zindex are reset issues

Due to the cssnano default configuration, resets are automatically reset z-index to 1, for example:

1classname {
2    z-index:1000;
3}
4
5after
6
7classname {
8    z-index:1;
9}

The Cssnano configuration needs to be optimized at this time. Postcssrc as follows:

 1/* eslint-disable no-unused-vars */
2module.exports = {
3  plugins: {
4    cssnano: {
5      preset: [
6        ‘advanced‘,
7        {
8          zindex: false,
9        }
10      ]
11    }
12  }
13}
When you load JS with on demand, the packaging code is particularly large

It is important to note that when you use the on-demand load feature and then do not extract all chunk of the packages, and then css turn on the sourcemap function, this is the case
The simplest approach is to css not use sourcemap features, such as:

1rules: [
2  {
3    loader: ‘postcss-loader‘,
4    options: {
5      sourceMap: false
6    }
7  }
8]
Advertising

The following is the author based on the Vue-cli template optimization vue and react packaging tools, consistent usage.

The following packages integrate all of the above optimizations, support single-page and multi-page applications, fully compatible vue-cli with generated template projects

Zz-webpack-vue

Zz-webpack-react

The following is an optimized comparison of the projects generated using a VUE-CLI in this group:

Before optimization:

Packaged


Analysis

After optimization:

Packaged

Analysis

can view specific optimization configuration, or directly in the project to try to use, have any questions welcome feedback at any time, is currently planning a unified upgradewebpack4

(Webpack Series II) Webpack packaging optimization Exploration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.