webpack对于公共资源的提炼之webpack.optimize.CommonsChunkPlugin

时间:2021-1-8 作者:admin

一、环境搭建

1、安装

mkdir webpack-li && cd webpack-li
npm init -y
npm install --save-dev webpack  webpack-dev-middleware webpack-dev-server webpack-manifest-plugin webpack-merge xml-loader clean-webpack-plugin css-loader csv-loader express file-loader html-webpack-plugin style-loader uglifyjs-webpack-plugin lodash

2、添加文件夹src,在src下面添加文件much1.js

mkdir src 
import _ from 'lodash';
function component() {
    var element = document.createElement('div');

    // Lodash(目前通过一个 script 脚本引入)对于执行这一行是必需的
    element.innerHTML = _.join(['Hello111', 'webpack'], ' ');
    element.classList.add('hello');
    element.classList.add('el-icon-upload');

    return element;
}

document.body.appendChild(component());

3、编辑webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
// var ManifestPlugin = require('webpack-manifest-plugin');
const webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
    entry: {
        index: './src/much1.js'
    },
    output: {
        filename: '[name].[chunkhash].js',
        path: path.resolve(__dirname, 'dist')
    },
    // devtool: 'inline-source-map',//生成内页source map 文件
    // devServer: {
    //     contentBase: './dist',
    //     hot: true
    // },
    module: {
        rules: [{
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            }, {
                test: /\.(png|svg|jpg|gif)$/,
                use: [
                    'file-loader'
                ]
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                use: [
                    'file-loader'
                ]
            },
            {
                test: /\.(csv|tsv)$/,
                use: [
                    'csv-loader'
                ]
            },
            {
                test: /\.xml$/,
                use: [
                    'xml-loader'
                ]
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        // new ManifestPlugin(),//编译前后文件映射
        // new UglifyJSPlugin(),//js压缩
        new HtmlWebpackPlugin({
            title: 'Output Management'
        }),
        // new webpack.optimize.CommonsChunkPlugin({
        //     name: 'common' // 指定公共 bundle 的名称。
        // }),
        // new webpack.NamedModulesPlugin(),
        // new webpack.HotModuleReplacementPlugin()
    ],
};

4、编译—-1个文件,引入modules模块–lodash

webpack    

二、测试过程

1、将webpack.config.js中的new webpack.optimize.CommonsChunkPlugin   代码放开,再次执行;生成的common.*.js中,主要包含文件关系window[“webpackJsonp”],默认只是提炼webpack 的样板(boilerplate)

Hash: 901d6379c09764da9d03
Version: webpack 3.10.0
Time: 586ms
                         Asset       Size  Chunks                    Chunk Names
 index.708570a5d9c1925e6cba.js     543 kB       0  [emitted]  [big]  index
common.d6716ad7b6bf34deabfe.js    5.82 kB       1  [emitted]         common
                    index.html  285 bytes          [emitted]         
   [0] ./src/much1.js 1.13 kB {0} [built]
   [2] (webpack)/buildin/global.js 509 bytes {0} [built]
   [3] (webpack)/buildin/module.js 517 bytes {0} [built]
    + 1 hidden module
Child html-webpack-plugin for "index.html":
     1 asset
       [2] (webpack)/buildin/global.js 509 bytes {0} [built]
       [3] (webpack)/buildin/module.js 517 bytes {0} [built]
        + 2 hidden modules

2、增加much2.js文件

import _ from 'lodash';

console.log(
  _.join(['Another', 'module', 'loaded!'], ' ')
);

更改webpack.config.js

entry: {
        much1: './src/much1.js',
        much2: './src/much2.js'
    },

执行编译,生成的common.*.js中,包含文件关系window[“webpackJsonp”],以及 公共插件lodash–2个文件,引入modules模块–lodash

Hash: a33a11dba68a5a50d0c1
Version: webpack 3.10.0
Time: 698ms
                         Asset       Size  Chunks                    Chunk Names
 much2.e93f8a1f67bb483eeb47.js  537 bytes       0  [emitted]         much2
 much1.b426830f89fd7baaf423.js    1.58 kB       1  [emitted]         much1
common.8a1f8f7618e51d034b44.js     547 kB       2  [emitted]  [big]  common
                    index.html  361 bytes          [emitted]         
   [1] ./src/much1.js 1.13 kB {1} [built]
   [2] (webpack)/buildin/global.js 509 bytes {2} [built]
   [3] (webpack)/buildin/module.js 517 bytes {2} [built]
   [4] ./src/much2.js 88 bytes {0} [built]
    + 1 hidden module
Child html-webpack-plugin for "index.html":
     1 asset
       [2] (webpack)/buildin/global.js 509 bytes {0} [built]
       [3] (webpack)/buildin/module.js 517 bytes {0} [built]
        + 2 hidden modules

3、修改much1.js的文件内容

element.innerHTML = _.join(['Hello', 'webpack'], ' ');

执行编译,发现common..js 和 much1..js的版本号发生改变

Hash: 017f08627b69bf79219d
Version: webpack 3.10.0
Time: 655ms
                         Asset       Size  Chunks                    Chunk Names
 much2.e93f8a1f67bb483eeb47.js  537 bytes       0  [emitted]         much2
 much1.f16da266b64d94bdfd24.js    1.58 kB       1  [emitted]         much1
common.d2f18d59fa51e749bf16.js     547 kB       2  [emitted]  [big]  common
                    index.html  361 bytes          [emitted]         
   [1] ./src/much1.js 1.13 kB {1} [built]
   [2] (webpack)/buildin/global.js 509 bytes {2} [built]
   [3] (webpack)/buildin/module.js 517 bytes {2} [built]
   [4] ./src/much2.js 88 bytes {0} [built]
    + 1 hidden module
Child html-webpack-plugin for "index.html":
     1 asset
       [2] (webpack)/buildin/global.js 509 bytes {0} [built]
       [3] (webpack)/buildin/module.js 517 bytes {0} [built]
        + 2 hidden modules

4、增加math.js

export function square(x) {
  return x * x;
}

export function cube(x) {
  return x * x * x;
}

更改much1.js

import _ from 'lodash';
import { cube } from './math.js';

function component() {
    var element = document.createElement('div');

    // Lodash(目前通过一个 script 脚本引入)对于执行这一行是必需的
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
    element.classList.add('hello');
    element.classList.add('el-icon-upload');
    var element = document.createElement('pre');
    element.innerHTML = [
        'Hello webpack!',
        '5 cubed is equal to ' + cube(5)
    ].join('\n\n');

    return element;
}

document.body.appendChild(component());

编译执行–2个文件,其中一个引入第3个js, math.js被编译在much1.*.js

5、在上一步的基础上,修改much2.js

import _ from 'lodash';
import { cube } from './math.js';

console.log(
  _.join(['Another', 'module', 'loaded!'], ' ')
);

编译执行–2个文件,都引入第3个js,math.js被编译在common.*.js,默认只是提炼webpack 的样板(boilerplate),以及被2个及以上文件引用过的js

6、修改webpack.config.js

new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, './node_modules')
          ) === 0
        )
      }
    }),

再次编译,生成的common..js中,只包含文件关系window[“webpackJsonp”] 和 lodash,只有node_modules中的模块被打包进common..js

7、修改webpack.config.js,再增加

new webpack.optimize.CommonsChunkPlugin({
            name: 'manifest',
            chunks: ['common']
        }),

编译执行,生成的common..js中,只包含文件关系window[“webpackJsonp”] ,common..js中包含 lodash

Hash: e89c001c2ded3524d449
Version: webpack 3.10.0
Time: 1441ms
                           Asset       Size  Chunks                    Chunk Names
  common.6b94cc3a187b7be511ae.js     541 kB       0  [emitted]  [big]  common
   much2.2d5b108f2c7292042637.js  914 bytes       1  [emitted]         much2
   much1.e5fff3acc8b12de04f6e.js    1.96 kB       2  [emitted]         much1
manifest.e0257ac8e9e9948ace74.js    5.88 kB       3  [emitted]         manifest
                      index.html  440 bytes          [emitted]         
   [0] ./src/math.js 94 bytes {1} {2} [built]
   [2] ./src/much1.js 1.11 kB {2} [built]
   [3] (webpack)/buildin/global.js 509 bytes {0} [built]
   [4] (webpack)/buildin/module.js 517 bytes {0} [built]
   [5] ./src/much2.js 122 bytes {1} [built]
    + 1 hidden module
Child html-webpack-plugin for "index.html":
     1 asset
       [2] (webpack)/buildin/global.js 509 bytes {0} [built]
       [3] (webpack)/buildin/module.js 517 bytes {0} [built]
        + 2 hidden modules

8、修改much1.js

element.innerHTML = _.join(['Hello33333', 'webpack'], ' ');

编译执行,只有much1..js 和 manifest..js 的版本号发送变化

Hash: 62d9c993ba573fda02fc
Version: webpack 3.10.0
Time: 705ms
                           Asset       Size  Chunks                    Chunk Names
  common.6b94cc3a187b7be511ae.js     541 kB       0  [emitted]  [big]  common
   much2.2d5b108f2c7292042637.js  914 bytes       1  [emitted]         much2
   much1.33e3d1b003899654d18d.js    1.97 kB       2  [emitted]         much1
manifest.cec9b6b2718268e923f3.js    5.88 kB       3  [emitted]         manifest
                      index.html  440 bytes          [emitted]         
   [0] ./src/math.js 94 bytes {1} {2} [built]
   [2] ./src/much1.js 1.11 kB {2} [built]
   [3] (webpack)/buildin/global.js 509 bytes {0} [built]
   [4] (webpack)/buildin/module.js 517 bytes {0} [built]
   [5] ./src/much2.js 122 bytes {1} [built]
    + 1 hidden module
Child html-webpack-plugin for "index.html":
     1 asset
       [2] (webpack)/buildin/global.js 509 bytes {0} [built]
       [3] (webpack)/buildin/module.js 517 bytes {0} [built]
        + 2 hidden modules

三、测试分析

1、webpack.optimize.CommonsChunkPlugin  默认提炼代码:webpack打包逻辑,在两个及以上页面出现过引入的js

2、vue-cli打包,使用了两次CommonsChunkPlugin——

new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    })

     第一次,将从node_modules引入的js文件打包到verdor.js;第二次,从第一步的verdor.js文件中抽离出webpack打包逻辑,形成manifest.js

     效果:优化页面性能。第一次打包的verdor.js变化几率较小,可以长久的存储在浏览器缓存中;第二次分离出来的逻辑manifest.js变化几率大,更新时重新加载js耗用的流量少,提升页面打开性能

     劣势:如果是多页面系统,verdor.js包含大量的公用js,某些可能是其他页面不需要使用的

声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。