HashedModuleIdsPlugin.js 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const createHash = require("crypto").createHash;
  7. class HashedModuleIdsPlugin {
  8. constructor(options) {
  9. this.options = Object.assign({
  10. hashFunction: "md5",
  11. hashDigest: "base64",
  12. hashDigestLength: 4
  13. }, options);
  14. }
  15. apply(compiler) {
  16. const options = this.options;
  17. compiler.plugin("compilation", (compilation) => {
  18. const usedIds = new Set();
  19. compilation.plugin("before-module-ids", (modules) => {
  20. modules.forEach((module) => {
  21. if(module.id === null && module.libIdent) {
  22. const id = module.libIdent({
  23. context: this.options.context || compiler.options.context
  24. });
  25. const hash = createHash(options.hashFunction);
  26. hash.update(id);
  27. const hashId = hash.digest(options.hashDigest);
  28. let len = options.hashDigestLength;
  29. while(usedIds.has(hashId.substr(0, len)))
  30. len++;
  31. module.id = hashId.substr(0, len);
  32. usedIds.add(module.id);
  33. }
  34. });
  35. });
  36. });
  37. }
  38. }
  39. module.exports = HashedModuleIdsPlugin;