webpack源码分析学习(一)

463 阅读2分钟

本文基于webpack@4.x.xwebpack-cli@3.x

1、打包后文件分析

webpack.config.js 基本配置

image.png

入口文件 index.js

console.log('打包测试内容'); 

module.export = '这是导出的内容';

执行npx webpack生成打包后文件

image.png

可以看到 webpack打包后 build中的 index.html,引用了build.js

image.png

在网页中打开 build中的 index.html ,正确打印出了 index.js中的 console

image.png

分析 build.js 文件

  • 打包后的的文件就是一个函数的自调用(匿名函数),当函数调用时传入一个对象
  • 作为参数传入的对象则是一个键值对
  • 这个键名则是当前被加载模块的文件名与某个模块的拼接
  • 这个键值就是一个函数,会将当前被加载模块的内容包裹在一个函数中
  • 这个函数将会在未来某个时间点被调用,同时接受一些参数,利用这些参数可以实现模块的加载操作

image.png

2、单文件打包后源码调试

对单文件打包后源码进行调试

函数传入的则是modules键值对参数

image.png

当前 installedModules对象为空对象

image.png

对 __webpack_require__函数进行某些属性的挂载

image.png

__webpack_require__.p 记录当前配置的公共路径

image.png

调用 webpack_require 函数

第一次函数执行完成之后完成对函数属性的挂载,__webpack_require__.s 其实就是 entry 配置的入口文件

image.png

进行入 webpack_require 函数中,

可以看到入参则为 './src/index.js'

// 此时会进入判断,判断是否解析过当前模块,
// 如果是则直接从 installedModules返回当前模块的exports
if (installedModules[moduleId]) {      
    return installedModules[moduleId].exports;
}

image.png

创建一个新的module对象,

并在installedModules记录当前解析的模块

  • i:表示当前解析对象的键(当前模块)
  • l:记录是否已经解析完成
  • exports:则为当前解析模块的exports

image.png

调用函数体

将this指向当前module的exports

image.png

传入当前module,module.exports, __webpack_require__ 函数

// 以及传入 __webpack_require__ 函数,主要是对当前模块依赖的模块进行递归解析
function (module, exports, __webpack_require__) {
        /* WEBPACK VAR INJECTION */ (function (module) {
          console.log('打包测试内容');

          module.export = '这是导出的内容';
          /* WEBPACK VAR INJECTION */
        }).call(
          this,
          __webpack_require__(
            /*! ./../node_modules/webpack/buildin/module.js */ './node_modules/webpack/buildin/module.js',
          )(module),
        );
},
  • 执行当前模块module的代码块
  • 将当前模块module.export 赋值
  • 当前module存在依赖模块会递归调用 __webpack_require__

image.png

函数体执行完成后

当前module对象的export为模块解析导出的exports

module.l = true 记录当前模块已解析加载

image.png

返回 module.exports

最后再返回 module.exports

image.png

在调试控制台打印出 index.js 中的 console

image.png

总结

本文只是简单对单文件打包后webpack的源码进行分析

如有不对欢迎指正 感谢阅读 仅供学习参考