webpack到底有什么作用
# 是什么
webpack 是一个前端打包工具
# 怎么用
# 作用
- 模块打包: 可以将不同模块的文件打包整合在一起,并且保证他们之间的引用正确,执行顺序
- 编辑兼容: 通过webpack的loader机制,不仅仅帮我们做代码polyfill,还可以编译诸如.less,.jsx,.vue这类在浏览器无法识别的格式文件,让我们可以在开发时使用新语法和新特性,提高开发效率。
- 能力扩展: 通过webpack的plugin机制, 在模块化打包的基础上可以进一步实现按需加载,代码压缩等一系列功能,提高打包自动化、工程效率、打包输出的质量
# 原理
# 模块打包运行原理
- 读取webpack的配置参数;
- 启动webpack,创建Compiler对象并开始解析项目;
- 从入口文件(entry)开始解析,并且找到其导入的依赖模块,递归遍历分析,形成依赖关系树;
- 对不同文件类型的依赖模块文件使用对应的Loader进行编译,最终转为Javascript文件;
- 整个过程中webpack会通过发布订阅模式,向外抛出一些hooks,而webpack的插件即可通过监听这些关键的事件节点,执行插件任务进而达到干预输出结果的目的。
最终Webpack打包出来的bundle文件是一个IIFE的执行函数。
# FAQ
3个变量,1个函数
- webpack_modules
- webpack_module_cache
- webpack_exports
- webpack_require
// webpack 5 打包的bundle文件内容
(() => { // webpackBootstrap
var __webpack_modules__ = ({
'file-A-path': ((modules) => { // ... })
'index-file-path': ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { // ... })
})
// 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;
}
// startup
// Load entry module and return exports
// This entry module can't be inlined because the eval devtool is used.
var __webpack_exports__ = __webpack_require__("./src/index.js");
})
上次更新: 2021/12/19, 18:05:42