Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can webpack report which file triggered a compilation in watch mode?

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.

like image 479
Aaron Cunnington Avatar asked Mar 31 '17 12:03

Aaron Cunnington


People also ask

Which command will run webpack in watch mode?

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" ... }

How does webpack watch work?

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.

What is webpack compilation?

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.

What are webpack plugins?

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.


1 Answers

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('===============================');
            }
        });
    }
}
like image 142
Schweinepriester Avatar answered Sep 19 '22 16:09

Schweinepriester