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