Webpack5Cache.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _getLazyHashedEtag = _interopRequireDefault(require("webpack/lib/cache/getLazyHashedEtag"));
  7. var _serializeJavascript = _interopRequireDefault(require("serialize-javascript"));
  8. var _webpack = require("webpack");
  9. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10. // eslint-disable-next-line import/extensions,import/no-unresolved
  11. class Cache {
  12. constructor(compiler, compilation, options) {
  13. this.compiler = compiler;
  14. this.compilation = compilation;
  15. this.options = options;
  16. }
  17. isEnabled() {
  18. return !!this.compilation.cache;
  19. }
  20. createCacheIdent(task) {
  21. const {
  22. outputOptions: {
  23. hashSalt,
  24. hashDigest,
  25. hashDigestLength,
  26. hashFunction
  27. }
  28. } = this.compilation;
  29. const hash = _webpack.util.createHash(hashFunction);
  30. if (hashSalt) {
  31. hash.update(hashSalt);
  32. }
  33. hash.update((0, _serializeJavascript.default)(task.cacheKeys));
  34. const digest = hash.digest(hashDigest);
  35. const cacheKeys = digest.substr(0, hashDigestLength);
  36. return `${this.compilation.compilerPath}/TerserWebpackPlugin/${cacheKeys}/${task.file}`;
  37. }
  38. get(task) {
  39. // eslint-disable-next-line no-param-reassign
  40. task.cacheIdent = task.cacheIdent || this.createCacheIdent(task); // eslint-disable-next-line no-param-reassign
  41. task.cacheETag = task.cacheETag || (0, _getLazyHashedEtag.default)(task.asset);
  42. return new Promise((resolve, reject) => {
  43. this.compilation.cache.get(task.cacheIdent, task.cacheETag, (err, result) => {
  44. if (err) {
  45. reject(err);
  46. } else if (result) {
  47. resolve(result);
  48. } else {
  49. reject();
  50. }
  51. });
  52. });
  53. }
  54. store(task, data) {
  55. return new Promise((resolve, reject) => {
  56. this.compilation.cache.store(task.cacheIdent, task.cacheETag, data, err => {
  57. if (err) {
  58. reject(err);
  59. } else {
  60. resolve(data);
  61. }
  62. });
  63. });
  64. }
  65. }
  66. exports.default = Cache;