浅析 webpack 打包流程(原理) 六 - 生成文件

接上文:浅析 webpack 打包流程(原理) 五 - 构建资源

八、生成(写入)文件

本阶段概述:
1.根据配置确定输出路径和文件名,创建目标文件夹及文件,将资源写入目标路径;
2.写入时,会循环处理sourceReplaceSource 实例的replacements,将其替换为真实字符串;
3.设置 stats 并打印构建信息。

回到 seal,执行this.summarizeDependencies(),得到this.fileDependenciesthis.contextDependenciesthis.missingDependencies后,触发了一系列处理/优化资源的钩子,然后回到Compiler.js的 compile 里的 compilation.seal 回调。

// /lib/Compiler.js
compilation.seal(err => {
  // seal 结束,执行回调  
  if (err) return callback(err);
  this.hooks.afterCompile.callAsync(compilation, err => {
    if (err) return callback(err);
    // callback 是调用 this.compile 时传入的 onCompiled 函数
    return callback(null, compilation);
  });
});

afterCompile钩子会触发插件 CachePlugin.js 订阅的相关事件,给 compiler 的属性_lastCompilationFileDependencies_lastCompilationContextDependencies分别赋值fileDependenciescontextDependencies

创建目标文件夹

执行 callback,即调用 this.compile 时传入的 onCompiled 函数:

// /lib/Compiler.js
const onCompiled = (err, compilation) => {
  // ...
  this.emitAssets(compilation, (err) => {
  //...
  });
}

emitAssets 方法负责的是构建资源输出的过程。它触发了 Compiler.hooks: emit,尔后在回调里执行:

// /lib/Compiler.js
emitAssets(compilation, callback) {
  let outputPath;
  const emitFiles = err => {
    asyncLib.forEachLimit()
  }

  this.hooks.emit.callAsync(compilation, err => {
    if (err) return callback(err);
    outputPath = compilation.getPath(this.outputPath); // 获取资源输出的路径
    this.outputFileSystem.mkdirp(outputPath, emitFiles); // 递归创建输出目录并输出资源
  });
}

outputPath 为配置里的 output.path,然后调用this.outputFileSystem.mkdirp创建文件夹。

创建目标文件并写入

成功创建目标文件夹后,执行回调emitFiles,方法里通过asyncLib.forEachLimit并行执行,对每个 file 资源文件进行路径拼接,将每个 source 源码转换为 buffer (为了性能提升),最后将文件写入真实目标路径:

// /lib/Compiler.js
asyncLib.forEachLimit(
  compilation.getAssets(),
  15,
  ({ name: file, source }, callback) => {
    //...
    const writeOut = (err) => {
      //...
      const targetPath = this.outputFileSystem.join(outputPath, targetFile); // 路径拼接,得到真实路径
      if (this.options.output.futureEmitAssets) {
        //... 判断重写入 及 gc释放内存(this.assets 相关重写 SizeOnlySource)
      } else {
        //... source 为 CachedSource 实例,content 为得到的资源
        let content = source.source();

        if (!Buffer.isBuffer(content)) {
          // buffer转换,在 node 中提升性能
          content = Buffer.from(content, 'utf8'); 
        }
        //... 写入文件
        this.outputFileSystem.writeFile(targetPath, content, (err) => {
          //...
          this.hooks.assetEmitted.callAsync(file, content, callback);
        });
      }
    };
    // 若目标文件路径包含/或\,先创建文件夹再写入
    if (targetFile.match(/\/|\\/)) {
      const dir = path.dirname(targetFile);
      this.outputFileSystem.mkdirp(this.outputFileSystem.join(outputPath, dir), writeOut);
    } else {
      writeOut();
    }
  },
  // 遍历完成的回调函数
  (err) => {
  }
);

上面let content = source.source() 中的 source 为 CachedSource 实例,它的 source 方法,进行了缓存判断,若无缓存通过this._source.source()获取资源。_source 为 ConcatSource 实例,它的 source 方法会遍历_source.children,如果不是字符串,则再执行 source 方法,是字符串就直接作为资源返回。源码如下:

// /node_modules/webpack-sources/lib/CachedSource.js
source() {
  if(typeof this._cachedSource !== "undefined") return this._cachedSource;
  return this._cachedSource = this._source.source();
}

// /node_modules/webpack-sources/lib/ConcatSource.js
source() {
  let source = "";
  const children = this.children;
  for(let i = 0; i < children.length; i++) {
    const child = children[i];
    source += typeof child === "string" ? child : child.source();
  }
  return source;
}

对于 ReplaceSource 实例,会执行其_replaceString方法,循环处理替换在之前【构建资源 -> 生成 chunk 资源 -> chunkTemplate -> 生成主体 chunk 代码 -> 生成每个 module 代码】 push 进去的replacements,得到替换后的字符串,合并返回resultStr

设置 stats 并打印构建信息

所有文件都创建写入完成后,执行回调:

// /lib/Compiler.js
this.hooks.afterEmit.callAsync(compilation, (err) => {
  if (err) return callback(err);
  return callback();
});

在触发Compiler.afterEmit: hooks的回调里执行 callback 即 onCompiled 里的this.emitAssets的回调:

// /lib/Compiler.js:298
this.emitRecords((err) => {
  const stats = new Stats(compilation);
  stats.startTime = startTime;
  stats.endTime = Date.now();
  this.hooks.done.callAsync(stats, (err) => {
    if (err) return finalCallback(err);
    return finalCallback(null, stats);
  });
});

this.emitRecords的回调里设置相关 stats,然后在Compiler.done: hooks 的回调里执行 finalCallback,即 webpack-cli/bin/cli.js 里的compiler.run的回调,即compilerCallback。清除缓存之后,执行:

// /node_modules/webpack-cli/bin/cli.js
const statsString = stats.toString(outputOptions);
const delimiter = outputOptions.buildDelimiter ? `${outputOptions.buildDelimiter}\n` : '';
if (statsString) stdout.write(`${statsString}\n${delimiter}`);

在 cli 里打印输出资源等相关信息。至此本次打包构建全部结束 ✅。

webpack 打包流程系列(未完):
浅析 webpack 打包流程(原理) - 案例 demo
浅析 webpack 打包流程(原理) 一 - 准备工作
浅析 webpack 打包流程(原理) 二 - 递归构建 module
浅析 webpack 打包流程(原理) 三 - 生成 chunk
浅析 webpack 打包流程(原理) 四 - chunk 优化
浅析 webpack 打包流程(原理) 五 - 构建资源
浅析 webpack 打包流程(原理) 六 - 生成文件

参考鸣谢:
webpack打包原理 ? 看完这篇你就懂了 !
webpack 透视——提高工程化(原理篇)
webpack 透视——提高工程化(实践篇)
webpack 4 源码主流程分析
[万字总结] 一文吃透 Webpack 核心原理
关于Webpack详述系列文章 (第三篇)

你可能感兴趣的:(浅析 webpack 打包流程(原理) 六 - 生成文件)