CachePlugin.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const asyncLib = require("async");
  7. class CachePlugin {
  8. constructor(cache) {
  9. this.cache = cache || {};
  10. this.FS_ACCURENCY = 2000;
  11. }
  12. apply(compiler) {
  13. if(Array.isArray(compiler.compilers)) {
  14. compiler.compilers.forEach((c, idx) => {
  15. c.apply(new CachePlugin(this.cache[idx] = this.cache[idx] || {}));
  16. });
  17. } else {
  18. compiler.plugin("compilation", compilation => {
  19. if(!compilation.notCacheable) {
  20. compilation.cache = this.cache;
  21. } else if(this.watching) {
  22. compilation.warnings.push(
  23. new Error(`CachePlugin - Cache cannot be used because of: ${compilation.notCacheable}`)
  24. );
  25. }
  26. });
  27. compiler.plugin("watch-run", (compiler, callback) => {
  28. this.watching = true;
  29. callback();
  30. });
  31. compiler.plugin("run", (compiler, callback) => {
  32. if(!compiler._lastCompilationFileDependencies) return callback();
  33. const fs = compiler.inputFileSystem;
  34. const fileTs = compiler.fileTimestamps = {};
  35. asyncLib.forEach(compiler._lastCompilationFileDependencies, (file, callback) => {
  36. fs.stat(file, (err, stat) => {
  37. if(err) {
  38. if(err.code === "ENOENT") return callback();
  39. return callback(err);
  40. }
  41. if(stat.mtime)
  42. this.applyMtime(+stat.mtime);
  43. fileTs[file] = +stat.mtime || Infinity;
  44. callback();
  45. });
  46. }, err => {
  47. if(err) return callback(err);
  48. Object.keys(fileTs).forEach(key => {
  49. fileTs[key] += this.FS_ACCURENCY;
  50. });
  51. callback();
  52. });
  53. });
  54. compiler.plugin("after-compile", function(compilation, callback) {
  55. compilation.compiler._lastCompilationFileDependencies = compilation.fileDependencies;
  56. compilation.compiler._lastCompilationContextDependencies = compilation.contextDependencies;
  57. callback();
  58. });
  59. }
  60. }
  61. /* istanbul ignore next */
  62. applyMtime(mtime) {
  63. if(this.FS_ACCURENCY > 1 && mtime % 2 !== 0)
  64. this.FS_ACCURENCY = 1;
  65. else if(this.FS_ACCURENCY > 10 && mtime % 20 !== 0)
  66. this.FS_ACCURENCY = 10;
  67. else if(this.FS_ACCURENCY > 100 && mtime % 200 !== 0)
  68. this.FS_ACCURENCY = 100;
  69. else if(this.FS_ACCURENCY > 1000 && mtime % 2000 !== 0)
  70. this.FS_ACCURENCY = 1000;
  71. }
  72. }
  73. module.exports = CachePlugin;