webpack可以报告哪个文件在监视模式下触发了编译?

问题描述 投票:8回答:3

我想让Webpack记录触发我的监视模式构建的文件。

我已经配置了一个监听watch-run编译器事件挂钩的插件,如下所示:

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

但我无法弄清楚更改的文件信息可能在哪里,如果它在那里。

Webpack文档在这方面确实缺乏。 Compiler Event Hook页面没有任何示例(只有一条消息可以解释即将推出的示例),并且old v1 documentation在详细阐述watching / compiler对象中可用的属性/方法方面并不是更好。

任何帮助或指导将不胜感激。

file logging build webpack watch
3个回答
13
投票

webpack文档不包含此类信息,并且很难包含编译器上可用的所有可能选项。但我想说,这是一个你应该通过阅读源代码或启动调试器并调查它们来探索可用选项的领域。我做了后者,发现更改的文件可用于:

watching.compiler.watchFileSystem.watcher.mtimes

这是一个对象,其中每个键是已更改文件的绝对路径,值是更改后的时间戳。当在配置的轮询间隔内保存了多个更改时,可能会有多个文件更改触发重新编译。

以下代码打印已更改的文件(文件也可能为空):

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();
});

一个示例输出是:

New build triggered, files changed:
  /path/to/app/src/components/item/Item.js
  /path/to/app/src/App.js

注意:此输出将在打印最终统计数据之前出现。


4
投票

在webpack 4中,您可以通过以下方式访问watcher

getChangedFiles(compiler) {
  const { watchFileSystem } = compiler;
  const watcher = watchFileSystem.watcher || watchFileSystem.wfs.watcher;

  return Object.keys(watcher.mtimes);
}

后者在watchRun钩子

compiler.hooks.watchRun.tapAsync('plugin name', (_compiler, done) => {
  const changedFile = this.getChangedFiles(_compiler)

  // ...

  return done();
});

2
投票

我在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("====================================")
      }
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.