Webpack 模块加载机制解析
本文深入解析 Webpack 打包后的代码结构,重点剖析 __webpack_require__ 函数的实现原理。通过示例代码展示模块如何被包装为匿名函数,以及模块参数 module、__webpack_exports__ 和 __webpack_require__ 的具体作用,帮助开发者理解前端模块化的底层机制。
Webpack 模块加载机制概述
Webpack 作为前端开发中备受青睐的模块打包工具,凭借其丰富的 loader 生态实现了多样化的功能需求。本文将通过一个具体的 JS 文件打包案例,深入探讨 Webpack 加载各个模块的内部机制。
示例源文件构建
构建示例源文件
为了清晰展示 Webpack 加载模块的原理,我们准备以下两个源文件进行演示:
hello.js
const hello = {
say: arg => {
console.info('hello ' + arg || 'world');
}
};
export default hello;
index.js
import Hello from './hello';
Hello.say('man');
其中,index.js 被指定为入口文件,并引用了 hello.js 模块。
Webpack 打包过程分析
执行 Webpack 打包
在命令行中执行命令 webpack index.js bundle.js 对入口文件进行打包,生成 bundle.js。其大体结构如下(为便于阅读,已省略部分冗余代码):

观察生成的文件结构可知,最终代码以 (function (modules) {})([模块1, 模块2]) 的形式启动。我们定义的模块被封装为一个个匿名函数,并以数组形式传递给外部匿名函数 function (modules) {}。在该匿名函数内部,定义了一个 __webpack_require__() 函数用于加载模块,最后通过 return __webpack_require__(__webpack_require__.s = 0); 语句加载第一个模块 index.js。
__webpack_require__ 函数原理
解析 __webpack_require__() 函数
该函数接收一个 moduleId 作为参数,该参数对应各个模块在数组中的索引位置。
function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/
if (installedModules[moduleId]) {
/******/
return installedModules[moduleId].exports;
/******/
}
/******/ // Create a new module (and put it into the cache)
/******/
var module = installedModules[moduleId] = {
/******/
i: moduleId,
/******/
l: false,
/******/
exports: {}
/******/
};
/******/
/******/ // Execute the module function
/******/
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/
module.l = true;
/******/
/******/ // Return the exports of the module
/******/
return module.exports;
/******/
}
其中,installedModules 用于缓存已执行过的模块。通过调用 modules[moduleId].call() 来执行模块代码,并最终返回模块的 exports 对象。
模块参数详解
模块接收的参数详解
以 hello.js 模块为例进行分析
(function (module, __webpack_exports__, __webpack_require__) {
"use strict";
const hello = {
say: arg => {
console.info('hello ' + arg || 'world');
}
};
/* harmony default export */
__webpack_exports__["a"] = (hello);
/***/
})
Webpack 会向模块传递 module, __webpack_exports__, __webpack_require__ 三个参数。前两个参数用于导出模块内部的变量,第三个参数则是前文介绍的 __webpack_require__() 的引用,用于导入其他模块。
以上内容即为本文的全部讲解,希望对读者的学习有所帮助,也欢迎大家继续支持本站。
生产环境怎么自动移除JS的console.log语句?
2026-11-03 10:59:54
面试刷题必备:怎么利用在线JS沙箱高效验证算法
2026-11-03 09:11:28
使用 Vite 构建 Phaser.js 项目的配置与资源管理
2026-11-02 10:26:07
webpack 自动清理 dist 文件夹的两种实现方法
2026-10-31 14:14:29
Docker部署Jackett完整指南:CLI与Compose配置及索引器使用
2026-10-31 12:57:10
