I would like for Webpack to log which file triggered my watch mode build.
I have configured a plugin that listens to the watch-run
compiler event hook like this:
function() {
this.plugin("watch-run", function(watching, callback) {
// maybe something in `watching` will indicate the changed file?
// when I find out what it is, `console.log` it here
callback();
});
}
// Example output: "/Users/aaron/git/test/index.js" was changed, new build triggered
But I cannot figure out where the changed file information might be, if it is there at all.
The Webpack documentation is really lacking in this area. The Compiler Event Hook page doesn't have any examples (only a message to explain that examples are coming soon), and the old v1 documentation is not much better at elaborating the properties/methods available in the watching
/compiler
object.
Any help or guidance would be greatly appreciated.
Below are the scripts to use it: "scripts": { "watch:webpack-build-dev": "webpack --watch --mode development", "clean-db": "rm -rf ./db && mkdir -p ./db", "local-dev": "npm run clean-db && npm run watch:webpack-build-dev" ... }
When using watch mode, webpack installs file watchers to all files, which were used in the compilation process. If any change is detected, it'll run the compilation again. When caching is enabled, webpack keeps each module in memory and will reuse it if it isn't changed.
The Compiler module of webpack is the main engine that creates a compilation instance with all the options passed through webpack CLI or webpack api or webpack configuration file. It is exported by webpack api under webpack. Compiler . The compiler is used by webpack by instantiating it and then calling the run method.
A webpack plugin is a JavaScript object that has an apply method. This apply method is called by the webpack compiler, giving access to the entire compilation lifecycle.
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('===============================');
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With