webpack原理/手写webpack

webpack构建流程分析

  • webpack的运行流程是一个串行的过程,从启动到结束会依次执行以下流程:首先会从配置文件和Shell语句中读取与合并参数,并初始化需要使用的插件和配置插件等执行环境所需要的参数;
  • 初始化完成后调用Compiler的run来真正启动webpack编译构建过程,webpack的构建流程包括compile,make,build,seal,emit阶段,执行完这些阶段就完成了构建过程;

初始化

entry-options启动

  • 从配置文件和Shell语句中读取与合并参数,得出最终的参数;

run实例

  • compiler:用上一步得到的参数初始化Compiler对象,加载所有配置的插件,执行对象的run方法开始执行编译;

编译构建

entry 确定入口
  • 根据配置中的entry确定需要打包文件的入口
make 编译模板
  • 从入口文件出发,调用所有配置的Loader对模块进行翻译,再找出该模块依赖的模块,在递归本步骤直到所有入口文件的依赖文件都经过了本步骤的处理
build module 完成模块编译
  • 经过上面使用loader翻译完所有模块,得到每个模块翻译完成的内容以及之间的依赖关系
seal 输出资源
  • 根据入口和模块之间的依赖关系,组装成一个个包含多个模块的Chunk,再把每个Chunk转换成一个单独的文件加入到输出列表,这步是可以修改输出内容的最后机会
emit 输出完成
  • 在确定好输出内容后,根据配置确定输出的路径和文件名,把文件内容写入到系统文件
|-- forestpack
    |-- dist
    |   |-- bundle.js
    |   |-- index.html
    |-- lib
    |   |-- compiler.js
    |   |-- index.js
    |   |-- parser.js
    |   |-- test.js
    |-- src
    |   |-- greeting.js
    |   |-- index.js
    |-- forstpack.config.js
    |-- package.json
forstpack.config.js vue项目中相当于vue.config.js
const path = require("path");

module.exports = {
  entry: path.join(__dirname, "./src/index.js"),
  output: {
    path: path.join(__dirname, "./dist"),
    filename: "bundle.js",
  },
};
在src下定义文件:
  • index.html
import {greeting } from "./greeting.js";

document.write(greeting("goodnight"));
  • greeting.js
export function greeting(name) {
  return "你好" + name;
}

compiler

const path = require("path");
const fs = require("fs");

module.exports = class Compiler {
  // 接收通过lib/index.js new Compiler(options).run()传入的参数,对应`forestpack.config.js`的配置
  constructor(options) {
    const { entry, output } = options;
    this.entry = entry;
    this.output = output;
    this.modules = [];
  }
  // 开启编译
  run() {}
  // 构建模块相关
  buildModule(filename, isEntry) {
    // filename: 文件名称
    // isEntry: 是否是入口文件
  }
  // 输出文件
  emitFiles() {}
};
  • 接收forsetpack.config.js配置参数,并初始化entry,output
  • 开启编译run方法,处理构建模块,收集依赖,输出文件等。
  • buildModule方法。主要用于构建模块(被run调用)
  • emitFiles方法。输出文件(同样被run方法调用)
posted @ 2022-09-08 17:28  Goodnighter  阅读(50)  评论(0)    收藏  举报