|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// This Webpack plugin ensures that package.json is watched for changes and |
| 4 | +// that appropriate actions are triggered, e.g. an eslint-loader recheck. |
| 5 | + |
| 6 | +class WatchPackageJsonPlugin { |
| 7 | + constructor(packageJsonPath) { |
| 8 | + this.packageJsonPath = packageJsonPath; |
| 9 | + this.erroneousFiles = []; |
| 10 | + } |
| 11 | + |
| 12 | + apply(compiler) { |
| 13 | + compiler.plugin('compilation', compilation => { |
| 14 | + const timestamp = compilation.fileTimestamps[this.packageJsonPath] || 0; |
| 15 | + |
| 16 | + if (timestamp > this.previousTimestamp && this.erroneousFiles.length) { |
| 17 | + this.erroneousFiles.forEach(filename => { |
| 18 | + compilation.fileTimestamps[filename] = timestamp; |
| 19 | + }); |
| 20 | + } |
| 21 | + }); |
| 22 | + |
| 23 | + compiler.plugin('emit', (compilation, callback) => { |
| 24 | + // Add package.json to the list of watched files. This needs to be done |
| 25 | + // for every compilation run since the list is rebuilt every time. |
| 26 | + compilation.fileDependencies.push(this.packageJsonPath); |
| 27 | + |
| 28 | + this.previousTimestamp = compilation.fileTimestamps[ |
| 29 | + this.packageJsonPath |
| 30 | + ] || 0; |
| 31 | + |
| 32 | + // First we extract all files related to any occurred errors. Then |
| 33 | + // we remove any request params that could have been added by a plugin, |
| 34 | + // loader or the user. |
| 35 | + this.erroneousFiles = compilation.errors |
| 36 | + .reduce( |
| 37 | + (acc, error) => { |
| 38 | + acc.push.apply(acc, error.dependencies); |
| 39 | + |
| 40 | + return acc; |
| 41 | + }, |
| 42 | + [] |
| 43 | + ) |
| 44 | + .map(entry => entry.request.replace(/\?.*$/)); |
| 45 | + |
| 46 | + callback(); |
| 47 | + }); |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +module.exports = WatchPackageJsonPlugin; |
0 commit comments