我正在开发一个 Webpack 5 插件,我需要手动触发一个监视文件的重新编译而不修改它(主要是为了做一些小众 HMR 的东西)。
我认为最简单的方法是让编译器相信文件已更改。我不想用 fs 实际更改文件。我已经查看了 webpack 源代码 - 欺骗 webpack 的 NodeWatchFileSystem 看起来很hacky。以另一种方式触发重新编译超出了我的范围。
我正在开发一个 Webpack 5 插件,我需要手动触发一个监视文件的重新编译而不修改它(主要是为了做一些小众 HMR 的东西)。
我认为最简单的方法是让编译器相信文件已更改。我不想用 fs 实际更改文件。我已经查看了 webpack 源代码 - 欺骗 webpack 的 NodeWatchFileSystem 看起来很hacky。以另一种方式触发重新编译超出了我的范围。
重新编译监视文件的最简单方法(无需实际更改它们)是更新它们的时间戳并将它们添加到 webpack 编译器上的修改后的文件中。然后,使 watching
无效,确保先清除 watcher
。
这将仅在这些文件上触发新构建,运行所有加载程序,并更新 HMR 等。
const time = Date.now();
const timestamps = new Map<string,FileSystemInfoEntry>();
const modifiedFiles = new Set<string>();
// Make an entry for each file path that should recompile
paths.forEach(path => {
timestamps.set(path,{
safeTime: time,timestamp: time,// accuracy: 0,});
modifiedFiles.add(path);
});
compiler.fileTimestamps = timestamps;
compiler.contextTimestamps = timestamps;
compiler.modifiedFiles = modifiedFiles;
// Trigger recompile
compiler.watching.watcher = null; // Otherwise watcher will pull in fresh file data,undoing the compiler modifications above
compiler.watching.invalidate(() => { // Triggers the recompile
console.log('Recompile finished');
});