当前位置: 首页 > 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 来定制打包行为。

相关文章:

  • Qt天气预报系统绘制温度曲线
  • 专业课复习笔记 4
  • 基于Python+MongoDB猫眼电影 Top100 数据爬取与存储
  • 地埋式燃气泄漏检测装置与地下井室可燃气体检测装置有什么区别
  • LLM(17):计算所有输入 token 的注意力权重
  • 【动态规划】子序列问题
  • Java 企业级开发设计模式全解析
  • 用户模块 - IP归属地功能实现与测试
  • AI Agent开发第50课-机器学习的基础-线性回归如何应用在商业场景中
  • PyTorch_自动微分模块
  • linux tar命令详解。压缩格式对比
  • C++访问MySQL
  • 联邦学习的深度解析,有望打破数据孤岛
  • 3.5/Q1,GBD数据库最新一区文章解读
  • rollout 是什么:机器学习(强化学习)领域
  • 【C/C++】各种概念联系及辨析
  • Socket 编程 TCP
  • 2025年PMP 学习五
  • Qt天气预报系统更新UI界面
  • 电路研究9.3.3——合宙Air780EP中的AT开发指南:HTTP(S)-HTTP GET 示例
  • 山东滕州一车辆撞向公交站台撞倒多人,肇事者被控制,案件已移交刑警
  • 2年就过气!ChatGPT催生的百万年薪岗位,大厂不愿意招了
  • 新加坡执政党人民行动党在2025年大选中获胜
  • 英国地方选举结果揭晓,工党保守党皆受挫
  • 哈马斯:愿与以色列达成为期5年的停火协议
  • 国际观察|韩国在政局多重不确定性中迎接总统选举