HashedModuleIdsPlugin.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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("./util/createHash");
  7. const validateOptions = require("schema-utils");
  8. const schema = require("../schemas/plugins/HashedModuleIdsPlugin.json");
  9. /** @typedef {import("../declarations/plugins/HashedModuleIdsPlugin").HashedModuleIdsPluginOptions} HashedModuleIdsPluginOptions */
  10. class HashedModuleIdsPlugin {
  11. /**
  12. * @param {HashedModuleIdsPluginOptions=} options options object
  13. */
  14. constructor(options) {
  15. if (!options) options = {};
  16. validateOptions(schema, options, "Hashed Module Ids Plugin");
  17. /** @type {HashedModuleIdsPluginOptions} */
  18. this.options = Object.assign(
  19. {
  20. context: null,
  21. hashFunction: "md4",
  22. hashDigest: "base64",
  23. hashDigestLength: 4
  24. },
  25. options
  26. );
  27. }
  28. apply(compiler) {
  29. const options = this.options;
  30. compiler.hooks.compilation.tap("HashedModuleIdsPlugin", compilation => {
  31. const usedIds = new Set();
  32. compilation.hooks.beforeModuleIds.tap(
  33. "HashedModuleIdsPlugin",
  34. modules => {
  35. for (const module of modules) {
  36. if (module.id === null && module.libIdent) {
  37. const id = module.libIdent({
  38. context: this.options.context || compiler.options.context
  39. });
  40. const hash = createHash(options.hashFunction);
  41. hash.update(id);
  42. const hashId = hash.digest(options.hashDigest);
  43. let len = options.hashDigestLength;
  44. while (usedIds.has(hashId.substr(0, len))) len++;
  45. module.id = hashId.substr(0, len);
  46. usedIds.add(module.id);
  47. }
  48. }
  49. }
  50. );
  51. });
  52. }
  53. }
  54. module.exports = HashedModuleIdsPlugin;