当前位置: 首页 > news >正文

webpack 的工作流程

Webpack 的工作流程可以分为以下几个核心步骤,我将结合代码示例详细说明每个阶段的工作原理:


1. 初始化配置

Webpack 首先会读取配置文件(默认 webpack.config.js),合并命令行参数和默认配置。

// webpack.config.js
module.exports = {entry: './src/index.js',      // 入口文件output: {                     // 输出配置filename: 'bundle.js',path: path.resolve(__dirname, 'dist')},module: {                     // 模块处理规则rules: [{ test: /\.js$/, use: 'babel-loader' },{ test: /\.css$/, use: ['style-loader', 'css-loader'] }]},plugins: [                    // 插件配置new HtmlWebpackPlugin()]
};

2. 解析入口文件

从入口文件开始构建依赖图(Dependency Graph)。

// src/index.js
import { hello } from './utils.js';
import './styles.css';hello();

Webpack 会解析入口文件的 import/require 语句,生成抽象语法树(AST):

// Webpack 内部伪代码
const entryModule = parseModule('./src/index.js');
const dependencies = entryModule.getDependencies(); // 获取依赖 ['./utils.js', './styles.css']

3. 递归构建依赖图

对每个依赖模块进行递归解析,形成完整的依赖关系树。

// Webpack 内部伪代码
function buildDependencyGraph(entry) {const graph = {};const queue = [entry];while (queue.length > 0) {const module = queue.pop();const dependencies = parseModule(module).getDependencies();graph[module] = {dependencies,code: transpile(module) // 使用 Loader 转换代码};queue.push(...dependencies);}return graph;
}

4. 使用 Loader 处理模块

根据配置的 Loader 对不同类型的文件进行转换。

// 当遇到 CSS 文件时
// 使用 css-loader 处理
module.exports = function(content) {// 将 CSS 转换为 JS 模块return `const css = ${JSON.stringify(content)};const style = document.createElement('style');style.textContent = css;document.head.appendChild(style);export default css;`;
};

5. 应用插件(Plugins)

在编译的不同阶段触发插件钩子。

// 自定义插件示例
class MyPlugin {apply(compiler) {compiler.hooks.emit.tap('MyPlugin', (compilation) => {console.log('资源生成完成,准备输出!');});}
}// 在配置中引用
plugins: [new MyPlugin()]

6. 代码优化与分块(Code Splitting)

根据配置进行代码分割。

// 动态导入示例
import(/* webpackChunkName: "utils" */ './utils').then(({ hello }) => {hello();
});// 输出结果:
// main.bundle.js
// utils.bundle.js (异步加载的 chunk)

7. 生成最终文件

将所有模块打包到一个或多个 bundle 中。

// Webpack 生成的 bundle 伪代码
(function(modules) {// Webpack 启动函数const installedModules = {};function __webpack_require__(moduleId) {// 模块缓存检查if (installedModules[moduleId]) {return installedModules[moduleId].exports;}// 创建新模块const module = installedModules[moduleId] = {exports: {}};// 执行模块函数modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);return module.exports;}// 加载入口模块return __webpack_require__("./src/index.js");
})({"./src/index.js": function(module, exports, __webpack_require__) {// 转换后的入口文件代码const utils = __webpack_require__("./src/utils.js");__webpack_require__("./src/styles.css");utils.hello();},"./src/utils.js": function(module, exports) {// 转换后的工具文件代码exports.hello = () => console.log("Hello Webpack!");}
});

8. 输出文件

将最终生成的 bundle 写入文件系统。

// Webpack 内部输出逻辑伪代码
const outputPath = path.resolve(config.output.path);
fs.writeFileSync(path.join(outputPath, config.output.filename),bundleCode
);

完整流程总结

  1. 初始化配置:合并配置参数
  2. 编译准备:创建 Compiler 对象
  3. 开始编译:从入口文件出发
  4. 模块解析:递归构建依赖图
  5. Loader 处理:转换非 JS 模块
  6. 插件干预:在关键生命周期执行插件
  7. 代码生成:生成运行时代码和模块闭包
  8. 输出文件:将结果写入目标目录

关键概念代码实现

模块解析器伪代码
class Module {constructor(filepath) {this.filepath = filepath;this.ast = null;this.dependencies = [];}parse() {const content = fs.readFileSync(this.filepath, 'utf-8');this.ast = parser.parse(content, { sourceType: 'module' });}collectDependencies() {traverse(this.ast, {ImportDeclaration: (path) => {this.dependencies.push(path.node.source.value);}});}
}

通过以上步骤,Webpack 完成了从源代码到最终打包文件的完整转换过程。实际项目开发中,可以通过调整配置文件的 entryoutputloaderplugins 来定制打包行为。

http://www.xdnf.cn/news/286723.html

相关文章:

  • 备忘录模式(Memento Pattern)
  • 56.[前端开发-前端工程化]Day03-webpack构建工具
  • Windows11 VS code 安装 Cline 调用 Github MCP 配置过程坑点汇总
  • 深入探索 51 单片机:从入门到实践的全面指南
  • ctfshow——web入门361~368
  • 电脑怎么分屏操作?
  • Gradio全解20——Streaming:流式传输的多媒体应用(5)——基于WebRTC的摄像头实时目标检测
  • N-Gram 模型
  • 慢sql处理流程和常见案例
  • Webug4.0靶场通关笔记16- 第20关文件上传(截断上传)
  • 数据结构——算法复杂度
  • 部署GM DC Monitor 一体化监控预警平台
  • Python 整理3种查看神经网络结构的方法
  • 3DGS-slam:splatam公式
  • 开源模型应用落地-qwen模型小试-Qwen3-8B-推理加速-vLLM(一)
  • Git 标签管理
  • 【STM32 学习笔记】GPIO输入与输出
  • Scrapy分布式爬虫实战:高效抓取的进阶之旅
  • 【NLP】30. 深入理解 In-Context Learning 的核心机制与策略
  • PrivKV: Key-Value Data Collection with Local Differential Privacy论文阅读
  • vue+element 导航 实现例子
  • HarmonyOS Device Connector(hdc)
  • linux 中inotify与inode的关系是什么?
  • PandasAI:对话式数据分析新时代
  • 实战设计模式之中介者模式
  • 基于Boost库、Jsoncpp、cppjieba、cpp-httplib等构建Boost搜索引擎
  • Lua 元表和元方法
  • 重名导致does not name a type
  • 青少年编程与数学 02-018 C++数据结构与算法 25课题、图像处理算法
  • 科学养生,开启健康生活新篇章