编写一个 webpack 插件在 emit 阶段调用 prettier

解读

这道题考察的是“把 Prettier 无缝塞进 webpack 构建链路”的能力。国内一线/二线厂在落地统一代码风格时,普遍会把格式化从“本地 git hook”下沉到“构建环节”,确保即使有人绕过了 lint-staged,最终产物仍然被强制美化。
emit 阶段是 webpack 把 chunk 落到内存的最后关口,此时所有源码已编译完、文件名已确定,但尚未写入磁盘,正是“批量格式化”的黄金时机。
面试官想看到:

  1. 你熟悉 webpack 插件的完整生命周期,知道在哪个钩子介入最安全;
  2. 你能正确同步/异步调用 Prettier,处理 parser 推断、配置合并、忽略文件等细节;
  3. 你对性能敏感,懂得用缓存、worker 池或增量策略,避免把 CI 拖垮;
  4. 你知道如何回写 assets、生成 source-map,并给出友好的错误提示,方便国内 Jenkins/GitLab CI 快速定位问题。

知识点

  1. webpack 插件基本骨架:compiler.hooks.emit.tapAsync/tapPromise,拿到 compilation.assets;
  2. prettier 三大 API:resolveConfig、format、check;
  3. 内存文件系统:compilation.assets[filename] = { source(), size() },需用 RawSource/ReplaceSource 回写;
  4. 异步调度:tapAsync 需手动 callback,tapPromise 需返回 Promise;
  5. 配置合并优先级:.prettierrc < plugin 入参 < 行内注释(@prettier/@format);
  6. 忽略策略:.prettierignore、prettier.format 的 filepath 参数用于推断 parser;
  7. 性能优化:cache-loader 思路 → 用 compilation.fileDependencies + 文件哈希做内存缓存;
  8. 错误处理:格式化失败不能阻断 emit,需用 compilation.warnings/errors 收集,兼容国内 CI 的 “warnings threshold” 规则;
  9. source-map 一致性:若已有 source-map,需用 source-map-merge 保证行列映射不漂移;
  10. 国内常见坑:
  • Windows 换行 CRLF 被 git 自动转换,需显式设置 endOfLine: 'lf';
  • 中文路径在 node < 14 时需 decodeURIComponent;
  • 大仓库(>2k 文件)下同步调用会阻塞事件循环,需用 worker_threads 或 piscina。

答案

// prettier-webpack-plugin.js
const { RawSource } = require('webpack-sources');
const prettier = require('prettier');
const path = require('path');

class PrettierWebpackPlugin {
  constructor(options = {}) {
    this.options = options;
  }

  apply(compiler) {
    const pluginName = 'PrettierWebpackPlugin';

    compiler.hooks.emit.tapAsync(pluginName, async (compilation, callback) => {
      try {
        // 1. 筛选需要处理的文件
        const assets = compilation.getAssets();
        const jsAssets = assets.filter(a => /\.(js|jsx|ts|tsx|mjs)$/.test(a.name));

        // 2. 并发格式化
        await Promise.all(
          jsAssets.map(async asset => {
            const origin = asset.source.source();
            const code = origin.toString();

            // 3. 取 Prettier 配置
            const filePath = path.join(compilation.compiler.context, asset.name);
            const config = await prettier.resolveConfig(filePath, {
              editorconfig: true,
              ...this.options.configOptions,
            });

            // 4. 调用 Prettier
            const formatted = prettier.format(code, {
              ...config,
              filepath: filePath,
            });

            // 5. 回写 asset
            compilation.updateAsset(asset.name, new RawSource(formatted));
          })
        );

        callback();
      } catch (err) {
        // 6. 错误收集,不阻断构建
        compilation.errors.push(err);
        callback();
      }
    });
  }
}

module.exports = PrettierWebpackPlugin;

使用示例(webpack.config.js):

const PrettierWebpackPlugin = require('./prettier-webpack-plugin');

module.exports = {
  mode: 'production',
  plugins: [
    new PrettierWebpackPlugin({
      configOptions: { useCache: true },
    }),
  ],
};

拓展思考

  1. 增量格式化:
    在 watch 模式下,通过 compilation.fileDependencies 与上次缓存的哈希对比,只对“变更文件”执行 prettier.format,可把 CI 耗时从 30s 降到 3s。
  2. 双引擎策略:
    把 ESLint 的 auto-fix 与 Prettier 合并到同一个插件,先让 ESLint 修语义,再让 Prettier 修风格,只需一次 emit 回写,减少 IO。
  3. 产物一致性校验:
    在 CI 最后一步执行 prettier --check dist,若发现仍有差异,直接 fail fast,防止有人手动改 dist 上线。
  4. 微前端场景:
    主应用与子应用独立仓库,插件支持“配置继承”——先读子应用目录下的 .prettierrc,再合并主仓库的 baseline,保证风格统一又不破坏子团队习惯。
  5. 合规与审计:
    国内金融、政务项目要求“构建可回溯”,插件可在格式化完成后生成 prettier-report.json,记录文件版本号、哈希、使用的规则集,作为审计附件随包上传至 Nexus 私有仓库。