阅读 247

工程化知识卡片 003:webpack 的运行时代码是什么?

大家好,我是山月。

这是我在掘金发表的前端工程化知识卡片集合 3/36

webpack 的 runtime,也就是 webpack 最后生成的代码,做了以下三件事:

  1. __webpack_modules__: 维护一个所有模块的数组。将入口模块解析为 AST,根据 AST 深度优先搜索所有的模块,并构建出这个模块数组。每个模块都由一个包裹函数 (module, module.exports, __webpack_require__) 对模块进行包裹构成。

  2. __webpack_require__(moduleId): 手动实现加载一个模块。对已加载过的模块进行缓存,对胃加载过的模块,执行 id 定位到 __webpack_modules__ 中的包裹函数,执行并返回 module.exports,并缓存

  3. __webpack_require__(0): 运行第一个模块,即运行入口模块

另外,当涉及到多个 chunk 的打包方式中,比如 code spliting,webpack 中会有 jsonp 加载 chunk 的运行时代码。

以下是 webpack runtime 的最简代码,配置示例可见 node-examples

/******/ var __webpack_modules__ = ([ /* 0 */, /* 1 */ /***/ ((module) => { module.exports = (...args) => args.reduce((x, y) => x + y, 0) /***/ }) /******/ ]); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/  /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/  // Check if module is in cache /******/  var cachedModule = __webpack_module_cache__[moduleId]; /******/  if (cachedModule !== undefined) { /******/  return cachedModule.exports; /******/  } /******/  // Create a new module (and put it into the cache) /******/  var module = __webpack_module_cache__[moduleId] = { /******/  // no module.id needed /******/  // no module.loaded needed /******/  exports: {} /******/  }; /******/  /******/  // Execute the module function /******/  __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/  /******/  // Return the exports of the module /******/  return module.exports; /******/ } /******/  /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. (() => { const sum = __webpack_require__(1) sum(3, 8) })(); 复制代码

webpack runtime 做进一步的精简,代码如下

const __webpack_modules__ = [() => {}] const __webpack_require = id => {   const module = { exports: {} }   const m = __webpack_modules__[id](module)   return module.exports } __webpack_require__(0)


作者:shanyue
链接:https://juejin.cn/post/7015562460509765662

文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐