webpack中CommonsChunkPlugin詳細教程(小結),

來源:互聯網
上載者:User

webpack中CommonsChunkPlugin詳細教程(小結),

本文介紹了webpack中CommonsChunkPlugin詳細教程(小結),分享給大家,也給自己留個筆記,具體如下:

1.demo結構:

2.package.json配置:

{ "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.多種打包情況(未使用CommonsChunkPlugin)

(1)單一入口,模組單一引用

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");

demo目錄下運行命令列 webpack或npm run webpack

jquery模組被一起打包到build.js

(2)單一入口,模組重複引用

webpack.config.js不變,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引用了chunk1、chunk2,chunk1又引用了chunk2,打包後:

build.js:

 ...省略webpack產生代碼/************************************************************************//******/ ([/* 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)多入口,模組單一引用,分檔案輸出

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: [   ]};

打包後檔案main.js,main1.js 內容與(2)build.js一致

(4)多入口,模組單一引用,單一檔案輸出

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與(2)一致

(5)多入口,模組重複引用,單檔案輸出

webpack.config.js與(4)一致

main.js

require("./chunk1");require("./chunk2");exports.main=1;

main1.js

require("./chunk1");require("./chunk2");require("./main");

報錯:ERROR in ./main1.js

Module not found: Error: a dependency to an entry point is not allowed

@ ./main1.js 3:0-17

4.使用CommonsChunkPlugin

(1)單一入口,模組單一引用,分檔案輸出:

webpack.config.js

var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");module.exports = { entry:  {  main:'./main.js', }, output: {  path:__dirname+'/dist',  filename: '[name].js'//不使用[name],並且外掛程式中沒有filename,這輸出檔案中只用chunk.js的內容,   main.js的內容不知跑哪裡去了 }, plugins: [  new CommonsChunkPlugin({    name:"chunk",    filename:"chunk.js"//忽略則以name為輸出檔案的名字,否則以此為輸出檔案名字  }) ]};

main.js

require("./chunk1");require("./chunk2");require("jquery");

輸出檔案main.js chunk.js,chunk1.js,chunck2.js,jquery都被打包到main.js裡,好像並沒有什麼卵用,但是頁面上使用的時候chunk.js必須在mian.js前引用

將chunk1.js,chunck2.js打包到chunk.js:

webpack.config.js

var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");module.exports = { entry:  {  main:'./main.js',  chunk: ["./chunk1", "./chunk2"],//外掛程式中name,filename必須以這個key為值 }, output: {  path:__dirname+'/dist',  filename: '[name].js'//不使用[name],並且外掛程式中沒有filename,  這輸出檔案中只用chunk.js的內容,main.js的內容不知跑哪裡去了 }, plugins: [  new CommonsChunkPlugin({    name:"chunk",   // filename:"chunk.js"//忽略則以name為輸出檔案的名字,否則以此為輸出檔案名字  }) ]};

(1)單一入口,模組重複引用,分檔案輸出(單一入口CommonsChunkPlugin能否將多次引用的模組打包到公用模組呢?):

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'//不使用[name],並且外掛程式中沒有filename,這輸出檔案中只用chunk.js的內容,main.js的內容不知跑哪裡去了 }, plugins: [  new CommonsChunkPlugin({    name:"chunk",   // filename:"chunk.js"//忽略則以name為輸出檔案的名字,否則以此為輸出檔案名字   minChunks:2  }) ]};

main.js

require("./chunk1");require("./chunk2");

chunk1.js

require("./chunk2");var chunk1=1;exports.chunk1=chunk1;

chunk2模組被引用了兩次

打包後,所有模組還是被打包到main.js中

(3)多入口,模組重複引用,分檔案輸出(將多次引用的模組打包到公用模組)

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'//不使用[name],並且外掛程式中沒有filename,  這輸出檔案中只用chunk.js的內容,main.js的內容不知跑哪裡去了 }, plugins: [  new CommonsChunkPlugin({    name:"chunk",   // filename:"chunk.js"//忽略則以name為輸出檔案的名字,否則以此為輸出檔案名字   minChunks:2  }) ]};

main.js,main1.js裡都引用chunk1,chunk2.

打包後:

chunk1,chunk2被打包到chunk.js,不再像3(3)chunk1,chunk2分別被打包到mian,mian1中。

5.將公用業務模組與類庫或架構分開打包

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'//不使用[name],並且外掛程式中沒有filename,    //這輸出檔案中只用chunk.js的內容,main.js的內容不知跑哪裡去了  },  plugins: [    new CommonsChunkPlugin({      name: ["chunk","common1","common2"],//頁面上使用的時候common2      //必須最先載入      // filename:"chunk.js"//忽略則以name為輸出檔案的名字,        //否則以此為輸出檔案名字      minChunks: 2    })  ]};

jquery被打包到common1.js,vue被打包到common2.js,chunk.js打包的是公用的業務模組(webpack用外掛程式CommonsChunkPlugin進行打包的時候,將符合引用次數(minChunks)的模組打包到name參數的數組的第一個塊裡(chunk),然後數組後面的塊依次打包(尋找entry裡的key,沒有找到相關的key就產生一個空的塊),最後一個塊包含webpack產生的在瀏覽器上使用各個塊的載入代碼,所以頁面上使用的時候最後一個塊必須最先載入)

將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;

打包後

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;/***/ }]);

相當於公用的業務代碼都打包到了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

6.參數minChunks: Infinity

看一下下面的配置會是什麼結果

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    })  ]};

main.js,main1.js共同引用的chunk1和chunk2會被打包到jquery.js裡

minChunks:2修改為minChunks:Infinity後,chunk1和chunk2都打包到main.js,main1.js裡

7.參數chunks

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"]    })  ]};

只有在main.js和main1.js中都引用的模組才會被打包的到公用模組(這裡即jquery.js)

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.