webpack构建流程

201 阅读1分钟

webpack构建流程

1.初始化参数

读取配置文件和命令行

2.开始编译

执行create() =>createCompiler(webpackOptions)

  • 初始化compiler 对象

  • 挂载plugins 执行run方法

  • 依据配置文件找到入口,开始解析文件构建AST语法树,找出依赖,递归下去;

    webpack.js
    
    //初始化compiler对象
    const compiler = new Compiler(options.context, options);
    //挂载插件
        for (const plugin of options.plugins) {
              if (typeof plugin === "function") {
                    plugin.call(compiler, compiler);
                } else {
                    plugin.apply(compiler);
    	}
    }  
        //这里的plugin.apply(compiler)注册事件 等待调用 不会立即执行plugin函数
        
      //webpack 内部在挂载插件的时候 是将配置属性转化为插件/赋值 进行处理 entry:"xxxx"
    new WebpackOptionsApply().process(options, compiler);
    
    Compiler.js
    // finalCallback onCompiled run
    // 执行run方法 在run 方法调用this.compile(onCompiled);
    
    this.compile(onCompiled);
    //在compile中
    const compilation = this.newCompilation(params);
    //执行的钩子函数 
    		compiler.hooks.make.tapAsync("EntryPlugin", (compilation, callback) => {
    		compilation.addEntry(context, dep, options, err => {
    			callback(err);
    		});
    	});
    
    
    
    

执行run方法

3.编译模板

配置文件中的loader 从入口模块开始编译所有依赖文件

4.完成编译并输出

递归完后,得到每个文件结果,包含每个模块以及他们之间的依赖关系,根据entry或分包配置生成代码块chunk;

5.写入文件

确定输出内容 路径+写入

hash

  • hash 每次构建生成新的hash
  • chunkhash 基于入口文件及其关联chunk构成 某个文件的改动只会影响到与其关联的chunk
  • contenthash css 文件内容改变 随之改变

webpack优化

通过externals

压缩代码

Tree Shaking(es6规范)- 可以在代码不运行的状态下,分析出不需要的代码