Webpack CommonsChunkPlugin detailed tutorial (Summary ),
This article introduces the detailed tutorial (Summary) of CommonsChunkPlugin webpack, shares it with you, and gives you some notes, as shown below:
1. demo structure:
2. package. json Configuration:
{ "name": "webpack-simple-demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "webpack": "webpack" }, "author": "", "license": "ISC", "dependencies": { "jquery": "^3.1.0", "vue": "^1.0.26" }, "devDependencies": { "css-loader": "^0.24.0", "style-loader": "^0.13.1", "webpack": "^1.13.2", "webpack-dev-server": "^1.15.1" }}
3. Multiple packaging conditions (CommonsChunkPlugin is not used)
(1) single entry, single module reference
Webpack. config. js
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");module.exports = { entry: { main:'./main.js', }, output: { path:__dirname+'/dist', filename: 'build.js' }, plugins: [ ]};
Main. js
require("jquery");
Run webpack or npm run webpack in the demo directory
The jquery module is packaged together into build. js.
(2) single entry, repeated module reference
Webpack. config. js remains unchanged, main. js:
require("./chunk1");require("./chunk2");
Chunk1.js:
require("./chunk2");var chunk1=1;exports.chunk1=chunk1;
Chunk2.js:
var chunk2=1;exports.chunk2=chunk2;
Main. js references chunk1 and chunk2, and chunk1 references chunk2. After packaging:
Build. js:
... Omit webpack Generation Code /*********************************** *************************************//* * *****/([/* 0 * // ***/function (module, exports, _ webpack_require _) {_ webpack_require _ (1); _ webpack_require _ (2 );/***/}, /* 1 * // ***/function (module, exports, _ webpack_require _) {_ webpack_require _ (2); var chunk1 = 1; exports. chunk1 = chunk1;/***/},/* 2 * // ***/function (module, exports) {var chunk2 = 1; exports. chunk2 = chunk2;/*****/}/******/]);
(3) multi-entry, single module reference, file output
Webpack. config. js
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");module.exports = { entry: { main:'./main.js', main1:'./main1.js' }, output: { path:__dirname+'/dist', filename: '[name].js' }, plugins: [ ]};
After packaging, the main. js file, main1.js content is consistent with (2) build. js
(4) multi-entry, single module reference, single file output
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");module.exports = { entry: { main:'./main.js', main1:'./main1.js' }, output: { path:__dirname+'/dist', filename: 'buid.js' }, plugins: [ ]};
Build. js is consistent with (2)
(5) multi-entry, repeated module reference, single file output
Webpack. config. js is consistent with (4)
Main. js
require("./chunk1");require("./chunk2");exports.main=1;
Main1.js
require("./chunk1");require("./chunk2");require("./main");
ERROR: ERROR in./main1.js
Module not found: Error: a dependency to an entry point is not allowed
@./Main1.js :0-17
4. Use CommonsChunkPlugin
(1) single entry, single module reference, and file output:
Webpack. config. js
Var CommonsChunkPlugin = require ("webpack/lib/optimize/CommonsChunkPlugin"); module. exports = {entry: {main :'. /main. js' ,}, output: {path :__ dirname + '/dist', filename:' [name]. js' // do not use [name], and the plug-in does not contain filename. Therefore, only chunk is used in the output file. js content, main. js content does not know where to go}, plugins: [new CommonsChunkPlugin ({name: "chunk", filename: "chunk. js "// ignore, the name is the name of the output file; otherwise, the name is})]};
Main. js
require("./chunk1");require("./chunk2");require("jquery");
Output file main. js chunk. js, chunk1.js, chunck2.js, and jquery are all packaged into main. in js, it seems that there is nothing to use, but chunk is used on the page. js must be in mian. references Before js
Package chunk1.js and chunck2.js to chunk. js:
Webpack. config. js
Var CommonsChunkPlugin = require ("webpack/lib/optimize/CommonsChunkPlugin"); module. exports = {entry: {main :'. /main. js', chunk :[". /chunk1 ",". /chunk2 "], // In the plug-in, the name and filename must use this key as the value}, output: {path :__ dirname + '/dist', filename:' [name]. js' // do not use [name], and the plug-in does not contain filename. Therefore, only chunk is used in the output file. js content, main. js content does not know where to go}, plugins: [new CommonsChunkPlugin ({name: "chunk", // filename: "chunk. js "// ignore, the name is the name of the output file; otherwise, the name is})]};
(1) single entry, repeated module references, and file output (can the single entry CommonsChunkPlugin package the referenced modules multiple times to the public module ?) :
Webpack. config. js
Var CommonsChunkPlugin = require ("webpack/lib/optimize/CommonsChunkPlugin"); module. exports = {entry: {main :'. /main. js', // main1 :'. /main1.js ',}, output: {path :__ dirname +'/dist', filename: '[name]. js' // do not use [name], and the plug-in does not contain filename. Therefore, only chunk is used in the output file. js content, main. js content does not know where to go}, plugins: [new CommonsChunkPlugin ({name: "chunk", // filename: "chunk. js "// ignore, the name is the name of the output file; otherwise, the name is minChunks: 2})]};
Main. js
require("./chunk1");require("./chunk2");
Chunk1.js
require("./chunk2");var chunk1=1;exports.chunk1=chunk1;
The chunk2 module is referenced twice.
After packaging, all modules are still packaged into main. js.
(3) multiple portals, repeated module references, and file output (package referenced modules into public modules)
Webpack. config. js
Var CommonsChunkPlugin = require ("webpack/lib/optimize/CommonsChunkPlugin"); module. exports = {entry: {main :'. /main. js', main1 :'. /main1.js ',}, output: {path :__ dirname +'/dist', filename: '[name]. js' // do not use [name], and the plug-in does not contain filename. Therefore, only chunk is used in the output file. js content, main. js content does not know where to go}, plugins: [new CommonsChunkPlugin ({name: "chunk", // filename: "chunk. js "// ignore, the name is the name of the output file; otherwise, the name is minChunks: 2})]};
Both main. js and main1.js reference chunk1 and chunk2.
After packaging:
Chunk1 and chunk2 are packaged into chunk. js, instead of being packaged into mian and mian1.
5. Separate and package public business modules from class libraries or frameworks
Webpack. config. js
Var CommonsChunkPlugin = require ("webpack/lib/optimize/CommonsChunkPlugin"); module. exports = {entry: {main :'. /main. js', main1 :'. /main1.js ', common1: ['jquery'], common2: ['vue ']}, output: {path: _ dirname +'/dist', filename: '[name]. js' // do not use [name], and the plug-in does not contain filename. // This output file only uses chunk. js content, main. js content does not know where to go}, plugins: [new CommonsChunkPlugin ({name: ["chunk", "common1", "common2"], // common2 when used on the page // It must be loaded first // filename: "chunk. js "// ignore, the name is the name of the output file, // otherwise the name is minChunks: 2})]};
Jquery is packaged into common1.js, and vue is packaged into common2.js and chunk. js packages public business modules (when webpack uses the plug-in CommonsChunkPlugin for packaging, it will match the number of references (minChunks) the module is packaged into the first chunk block of the name parameter array, and then the blocks after the array are packed in sequence (find the key in the entry, an empty block is generated if no related key is found. The last block contains the Load Code of each block generated by webpack in the browser, therefore, the last block must be loaded first when used on the page)
Change webpack. config. js
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");module.exports = { entry: { main: './main.js', main1: './main1.js', jquery:["jquery"], vue:["vue"] }, output: { path: __dirname + '/dist', filename: '[name].js' }, plugins: [ new CommonsChunkPlugin({ name: ["common","jquery","vue","load"], minChunks:2 }) ]};
Main. js
require("./chunk1");require("./chunk2");var jq=require("jquery");console.log(jq);
Main1.js
require("./chunk1");require("./chunk2");var vue=require("vue");console.log(vue);exports.vue=vue;
After packaging
Common. js
webpackJsonp([4,5],[/* 0 */,/* 1 */,/* 2 *//***/ function(module, exports, __webpack_require__) { __webpack_require__(3); var chunk1=1; exports.chunk1=chunk1;/***/ },/* 3 *//***/ function(module, exports) { var chunk2=1; exports.chunk2=chunk2;/***/ }]);
It is equivalent to packaging public business code into common. js.
Load. js
/******/ (function(modules) { // webpackBootstrap/******/ // install a JSONP callback for chunk loading/******/ var parentJsonpFunction = window["webpackJsonp"];/******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules) {/******/ // add "moreModules" to the modules object,/******/ // then flag all "chunkIds" as loaded and fire callback/******/ var moduleId, chunkId, i = 0, callbacks = [];/******/ for(;i < chunkIds.length; i++) {/******/ chunkId = chunkIds[i];/******/ if(installedChunks[chunkId])/******/ callbacks.push.apply(callbacks, installedChunks[chunkId]);/******/ installedChunks[chunkId] = 0;/******/ }/******/ for(moduleId in moreModules) {/******/ modules[moduleId] = moreModules[moduleId];/******/ }/******/ if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules);/******/ while(callbacks.length)/******/ callbacks.shift().call(null, __webpack_require__);/******/ if(moreModules[0]) {/******/ installedModules[0] = 0;/******/ return __webpack_require__(0);/******/ }/******/ };/******/ // The module cache/******/ var installedModules = {};/******/ // object to store loaded and loading chunks/******/ // "0" means "already loaded"/******/ // Array means "loading", array contains callbacks/******/ var installedChunks = {/******/ 5:0/******/ };/******/ // The require function/******/ function __webpack_require__(moduleId) {/******/ // Check if module is in cache/******/ if(installedModules[moduleId])/******/ return installedModules[moduleId].exports;/******/ // Create a new module (and put it into the cache)/******/ var module = installedModules[moduleId] = {/******/ exports: {},/******/ id: moduleId,/******/ loaded: false/******/ };/******/ // Execute the module function/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);/******/ // Flag the module as loaded/******/ module.loaded = true;/******/ // Return the exports of the module/******/ return module.exports;/******/ }/******/ // This file contains only the entry chunk./******/ // The chunk loading function for additional chunks/******/ __webpack_require__.e = function requireEnsure(chunkId, callback) {/******/ // "0" is the signal for "already loaded"/******/ if(installedChunks[chunkId] === 0)/******/ return callback.call(null, __webpack_require__);/******/ // an array means "currently loading"./******/ if(installedChunks[chunkId] !== undefined) {/******/ installedChunks[chunkId].push(callback);/******/ } else {/******/ // start chunk loading/******/ installedChunks[chunkId] = [callback];/******/ var head = document.getElementsByTagName('head')[0];/******/ var script = document.createElement('script');/******/ script.type = 'text/javascript';/******/ script.charset = 'utf-8';/******/ script.async = true;/******/ script.src = __webpack_require__.p + "" + chunkId + "." + ({"0":"jquery","1":"main","2":"main1","3":"vue","4":"common"}[chunkId]||chunkId) + ".js";/******/ head.appendChild(script);/******/ }/******/ };/******/ // expose the modules object (__webpack_modules__)/******/ __webpack_require__.m = modules;/******/ // expose the module cache/******/ __webpack_require__.c = installedModules;/******/ // __webpack_public_path__/******/ __webpack_require__.p = "";/******/ })/************************************************************************//******/ ([]);
Load. js must be loaded first.
6. Parameter minChunks: Infinity
See what the configuration result will be
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");module.exports = { entry: { main: './main.js', main1: './main1.js', jquery:["jquery"] }, output: { path: __dirname + '/dist', filename: '[name].js' }, plugins: [ new CommonsChunkPlugin({ name: "jquery", minChunks:2 }) ]};
Chunk1 and chunk2 referenced by main. js and main1.js will be packaged into jquery. js.
After minChunks: 2 is changed to minChunks: Infinity, both chunk1 and chunk2 are packaged into main. js and main1.js.
7. The chunks Parameter
Webpack. config. js
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");module.exports = { entry: { main: './main.js', main1: './main1.js', jquery:["jquery"] }, output: { path: __dirname + '/dist', filename: '[name].js' }, plugins: [ new CommonsChunkPlugin({ name: "jquery", minChunks:2, chunks:["main","main1"] }) ]};
Only modules referenced in main. js and main1.js are packaged into public modules (jquery. js)
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.