上一章講的是providerPlugin
,和這一章依舊沒有絲毫關係,這一章講的是CommonsChunkPlugin
,說實在的,這個插件略複雜,我還沒徹底搞懂,大概是還沒到那麼深我就已經選擇其餘解決方案了吧,因此這裏只講一些基本用法。jquery
這個插件就是用來提取公共代碼的,能夠這麼說,若是一個方法被兩個入口文件調用,那麼這個方法將被打包到這兩個文件中,會造成代碼冗餘,這個插件能夠將這個方法提取出來,放到第三個文件中,經過在引入入口文件以前引入第三個文件,就能夠避免冗餘的代碼打包webpack
爲了更深入理解,須要舉個栗子web
搭建環境npm
+ 0x007-common-chunk-plugin + src - webpack.config.js
安裝依賴segmentfault
$ npm init -y $ npm install --save-dev webpack
修改配置ide
var path = require('path') module.exports = { entry : path.resolve(__dirname, 'src/index.js'), output : { path : path.resolve(__dirname, 'dist'), filename: '[name].js' } }
添加其餘入口文件工具
entry : { index1: path.resolve(__dirname, 'src/index.js'), index2: path.resolve(__dirname, 'src/index2.js') }, // ./src/index.js var timestamp = require('./utils') timestamp() // ./src/index2.js var timestamp = require('./utils') timestamp()
添加工具類./src/utils.js
ui
export default function () { console.log(new Date().getTime()) }
打包並查看文件插件
// ./dist.index1.js ... "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony default export */ __webpack_exports__["default"] = (function () { console.log(new Date().getTime()) }); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { var timestamp = __webpack_require__(0) timestamp() ...
// ./dist/index2.js ... "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony default export */ __webpack_exports__["default"] = (function () { console.log(new Date().getTime()) }); /***/ }), /* 1 */, /* 2 */ /***/ (function(module, exports, __webpack_require__) { var timestamp = __webpack_require__(0) timestamp() ...
能夠看到,一樣的的utils
分別被打包到了index1.js
和index2.js
,存在代碼冗餘。code
commonChunkPlugin
修改配置文件
var path = require('path') var webpack = require('webpack') module.exports = { entry : { index1: path.resolve(__dirname, 'src/index.js'), index2: path.resolve(__dirname, 'src/index2.js') }, output : { path : path.resolve(__dirname, 'dist'), filename: '[name].js' }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: "vendor" }) ] }
再次打包,能夠發現,多了一個vendor.js
,裏面是utils.js
的方法,查看index1.js
和index2.js
能夠發現,原先重複的地方沒了,所以咱們就能夠經過引入vendor.js
、index1.js
和vendor.js
、index2.js
來達到對公共代碼的提取和分離。
// ./dist/vendor.js "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony default export */ __webpack_exports__["default"] = (function () { console.log(new Date().getTime()) });
// ./dist/index1.js webpackJsonp([1],[ /* 0 */, /* 1 */ /***/ (function(module, exports, __webpack_require__) { var timestamp = __webpack_require__(0) timestamp() /***/ }) ],[1]);
// ./dist/index2.js webpackJsonp([0],{ /***/ 2: /***/ (function(module, exports, __webpack_require__) { var timestamp = __webpack_require__(0) timestamp() /***/ }) },[2]);
new webpack.optimize.CommonsChunkPlugin({ name : ["jquery", "lodash"], minChunks: Infinity, })
固然還有許多更加複雜的用法,還請看[webpack關於commonChunkPlugin章節][2]
### 0x005 資源
- [源代碼][3]