Can webpack report which file triggered a compilation in watch mode?
This kind of information is not covered by the webpack documentation and it would be difficult to include every possible option that is available on the compiler. But I would say that this is an area where you should explore the available options by either reading the source code or spinning up a debugger and investigate them. I did the latter and found that the changed files are available in:
watching.compiler.watchFileSystem.watcher.mtimes
This is an object where each key is an absolute path to a file that has been changed and the value is the timestamp when it has been changed. It is possible to have more than one file change that triggers the recompilation, when multiple changes have been saved within the configured poll interval.
The following code prints the files that have been changed (the files might also be empty):
this.plugin("watch-run", (watching, done) => {
const changedTimes = watching.compiler.watchFileSystem.watcher.mtimes;
const changedFiles = Object.keys(changedTimes)
.map(file => `\n ${file}`)
.join("");
if (changedFiles.length) {
console.log("New build triggered, files changed:", changedFiles);
}
done();
});
An example output of this is:
New build triggered, files changed:
/path/to/app/src/components/item/Item.js
/path/to/app/src/App.js
Note: This output will come before the final stats are printed.
For Webpack 5, since watchFileSystem.watcher.mtimes
has been removed, I've changed the excellent answer by Sander to this:
class WatchRunPlugin {
apply(compiler) {
compiler.hooks.watchRun.tap('WatchRun', (comp) => {
if (comp.modifiedFiles) {
const changedFiles = Array.from(comp.modifiedFiles, (file) => `\n ${file}`).join('');
console.log('===============================');
console.log('FILES CHANGED:', changedFiles);
console.log('===============================');
}
});
}
}
The plugin I used for this in Webpack 4:
class WatchRunPlugin {
apply(compiler) {
compiler.hooks.watchRun.tap('WatchRun', (comp) => {
const changedTimes = comp.watchFileSystem.watcher.mtimes;
const changedFiles = Object.keys(changedTimes)
.map(file => `\n ${file}`)
.join('');
if (changedFiles.length) {
console.log("====================================")
console.log('NEW BUILD FILES CHANGED:', changedFiles);
console.log("====================================")
}
});
}
}