对webpack打包后的代码进行分析

打包前

src目录下

  • index.js
 console.log('hello world');
 var a = require('./a.js');
 console.log(a)
  • a.js
var a = 1;
require('./b.js')
exports.c = 3;
console.log(a.log())
  • b.js
 console.log('b')

打包后

(function(){
    // 把模块放到一个对象中
    // 键名为路径
    var webpack_modules = {
        // 用eval是因为方便报错
        // //# sourceURL=webpack://webpackstudy/./src/b.js?  (这个是告诉浏览器报错的显示路径)
        './src/a.js':(module,exports,reuqire) => {
            eval("var a = 1;\r\nreuqire(/*! ./b.js */ \"./src/b.js\")\r\nexports.c = 3;\r\nconsole.log(a.log())\n\n//# sourceURL=webpack://webpackstudy/./src/a.js?");
        },
        // 因为b没有依赖所以没有参数
        './src/b.js':() => {
            eval("console.log('b')\n\n//# sourceURL=webpack://webpackstudy/./src/b.js?");
        },
        './src/index.js':function(module,exports,reuqire){
            eval("console.log('hello world');\r\nvar a = reuqire(/*! ./a.js */ \"./src/a.js\");\r\nconsole.log(a)\n\n//# sourceURL=webpack://webpackstudy/./src/index.js?");
        }
    }

    // 缓存加载过的模块
    var module_cache = {};

    // 导入函数 moduleId为模块id
    function reuqire(moduleId) {
        // 如果加载过,把以前的值返回出来
        var cachedModule = module_cache[moduleId];
        if (cachedModule !== undefined) {
          return cachedModule.exports;
        }

        // 没加载过生成一个对象
        var module = module_cache[moduleId] = {
            exports: {}
        };

        // 运行模块的函数 
        webpack_modules[moduleId](module,module.exports,reuqire);

        // 最终的结果会保存到module对象中
        return module.exports;
    }

    // 默认会加载src下的index.js
    var __webpack_exports__ = reuqire("./src/index.js");
})()