当插件依赖外部 JSON 配置时,如何监听文件变化并热更新
解读
Prettier 插件体系里,.prettierrc、.prettierrc.json 乃至自定义路径的 JSON 文件都可能成为“外部配置”。
国内真实场景下,团队常把“项目级共享配置”抽成独立 npm 包,再在仓库根目录放一份 prettier.config.json 做覆盖;CI、本地、VS Code 插件、WebStorm 都要秒级感知变更,否则就会出现“本地格式化完,CI 又报格式错误”的尴尬。
面试官问“监听+热更新”,并不是让你背诵 fs.watch API,而是考察三条线:
- 插件生命周期:Prettier 3.x 以后插件是 ESM,入口只会在进程启动时加载一次,没有官方“热替换”钩子;
- 配置缓存:Prettier 内部对配置做了 lru-cache,文件 mtime 不变就直接复用;
- 进程模型:VS Code 插件宿主持久化,CLI 是一次性进程,两者对“热”的定义不同。
因此,候选人必须给出“在插件里自己拆缓存 + 向宿主发信号”的完整闭环,而不是简单说一句“用 chokidar”。
知识点
- Prettier 配置解析链路
resolveConfig(filePath, options)→loadConfig()→cosmiconfig()→ 最终mergeOverrides();其中options.config可指定绝对路径,命中后会把文件路径和 mtime 写进内部configCache。 - 插件入口签名
export const parsers = { ... }; export const printers = { ... };模块只会被import()一次,没有 dispose 钩子。 - 文件监听选型
- Node 原生
fs.watch:Linux 下递归目录需自写 DFS,且存在句柄耗尽风险; chokidar:国内项目标配,已内置在 @vue/cli、vite 等工具,npm 月下载量 6 亿+,可放心使用;- VS Code 插件环境:若插件跑在 Extension Host,需用
vscode.createFileSystemWatcher,否则会出现双 watcher 内存泄漏。
- Node 原生
- 缓存失效策略
把“配置对象 + 文件 mtime”作为复合 key;change 事件触发后,先delete require.cache[absolutePath](JSON 文件仍挂在 require.cache 上),再prettier.clearConfigCache(),最后抛一个自定义异常让宿主感知“配置已更新,请重试”。 - 信号通信
CLI 场景:插件里直接console.warn('[prettier-plugin-xxx] config reloaded'),用户再次执行命令即可;
编辑器场景:通过vscode.commands.executeCommand('prettier.reload')触发官方重载命令,或发送DidChangeConfiguration通知。
答案
下面给出一套可直接落地的“双模式”代码骨架,兼顾 CLI 与 VS Code,全部用同步逻辑写,方便面试官一眼看懂。
// prettier-plugin-custom/index.js
import { readFileSync, statSync } from 'node:fs';
import { createRequire } from 'node:module';
import path from 'node:path';
let configPath = ''; // 外部 JSON 绝对路径
let lastMtime = 0; // 缓存时间戳
let cachedOptions = null; // 缓存配置
/* 1. 解析并缓存外部 JSON */
function loadExternalConfig() {
const stat = statSync(configPath);
if (stat.mtimeMs === lastMtime) return cachedOptions;
const require = createRequire(import.meta.url);
delete require.cache[configPath]; // 清掉 JSON 缓存
cachedOptions = JSON.parse(readFileSync(configPath, 'utf8'));
lastMtime = stat.mtimeMs;
return cachedOptions;
}
/* 2. 插件入口:把外部配置合并到 prettier options */
export const options = {
customConfigPath: {
type: 'path',
category: 'Config',
default: '',
description: '外部 JSON 配置文件路径',
},
};
export const parsers = {
babel: {
...builtinParsers.babel, // 继承官方 babel parser
preprocess(text, options) {
// 只在第一次或路径变化时初始化 watcher
if (options.customConfigPath !== configPath) {
configPath = path.resolve(options.customConfigPath);
startWatcher();
}
const externalOpts = loadExternalConfig();
Object.assign(options, externalOpts); // 合并到当前格式化选项
return text;
},
},
};
/* 3. 文件监听 + 热更新 */
let watcher = null;
function startWatcher() {
if (watcher) watcher.close();
if (!configPath) return;
// 判断是否在 VS Code Extension Host
const isVscode = typeof vscode !== 'undefined';
if (isVscode) {
const pattern = new vscode.RelativePattern(path.dirname(configPath), path.basename(configPath));
watcher = vscode.workspace.createFileSystemWatcher(pattern, false, false, false);
watcher.onDidChange(() => {
reloadConfig();
vscode.commands.executeCommand('prettier.reload');
});
} else {
// CLI 场景:用 chokidar,无 vscode 变量
import('chokidar').then(({ default: chokidar }) => {
watcher = chokidar.watch(configPath, { disableGlobbing: true });
watcher.on('change', () => {
reloadConfig();
console.warn(`[prettier-plugin-custom] ${configPath} 已热更新`);
});
});
}
}
function reloadConfig() {
lastMtime = 0; // 强制失效
prettier.clearConfigCache(); // 清掉 prettier 全局缓存
}
使用方式
- 项目根目录新建
prettier.config.json; .prettierrc.js里写:module.exports = { plugins: ['prettier-plugin-custom'], customConfigPath: './prettier.config.json', };- 运行
npx prettier --write .后,改动 JSON 文件,再次保存即可看到热更新提示;VS Code 用户保存后格式化结果秒级生效,无需重启窗口。
拓展思考
- 多进程竞争
在大型 Monorepo 里,可能同时跑prettier --write和lint-staged,两条进程都启 watcher 会重复触发。解决思路:用“单例文件锁”或“命名管道”保证同一机器只起一个 watcher,变更后通过process.emit('prettier:config:reload')广播。 - 配置校验
外部 JSON 若格式错误,reload 时直接抛异常会导致整个格式化失败。可在loadExternalConfig里先用jsonc-parser做容错解析,再按 JSON Schema 校验,给出中文错误提示,避免“格式化突然罢工”的投诉。 - 性能权衡
对 10 万行级仓库,每次 reload 都prettier.clearConfigCache()会清空所有文件缓存,可能让下一次格式化慢 200 ms。可细化到“仅清该 JSON 影响到的文件”,通过自定义configFile字段打标,实现更细粒度缓存淘汰。 - 标准化提案
社区已向 Prettier 官方提过“插件 dispose 钩子”议题,若未来版本落地,可去掉自建 watcher,直接在dispose()里watcher.close(),实现更优雅的内存回收。面试时可以主动提及“我在跟踪 #12246 提案”,体现对上游的持续关注。