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

      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1392.html