NamedModulesPlugin.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 RequestShortener = require("./RequestShortener");
  8. const getHash = str => {
  9. const hash = createHash("md4");
  10. hash.update(str);
  11. const digest = /** @type {string} */ (hash.digest("hex"));
  12. return digest.substr(0, 4);
  13. };
  14. class NamedModulesPlugin {
  15. constructor(options) {
  16. this.options = options || {};
  17. }
  18. apply(compiler) {
  19. compiler.hooks.compilation.tap("NamedModulesPlugin", compilation => {
  20. compilation.hooks.beforeModuleIds.tap("NamedModulesPlugin", modules => {
  21. const namedModules = new Map();
  22. const context = this.options.context || compiler.options.context;
  23. for (const module of modules) {
  24. if (module.id === null && module.libIdent) {
  25. module.id = module.libIdent({ context });
  26. }
  27. if (module.id !== null) {
  28. const namedModule = namedModules.get(module.id);
  29. if (namedModule !== undefined) {
  30. namedModule.push(module);
  31. } else {
  32. namedModules.set(module.id, [module]);
  33. }
  34. }
  35. }
  36. for (const namedModule of namedModules.values()) {
  37. if (namedModule.length > 1) {
  38. for (const module of namedModule) {
  39. const requestShortener = new RequestShortener(context);
  40. module.id = `${module.id}?${getHash(
  41. requestShortener.shorten(module.identifier())
  42. )}`;
  43. }
  44. }
  45. }
  46. });
  47. });
  48. }
  49. }
  50. module.exports = NamedModulesPlugin;