EvalDevToolModuleTemplatePlugin.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { RawSource } = require("webpack-sources");
  7. const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
  8. const cache = new WeakMap();
  9. class EvalDevToolModuleTemplatePlugin {
  10. constructor(options) {
  11. this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]";
  12. this.moduleFilenameTemplate =
  13. options.moduleFilenameTemplate ||
  14. "webpack://[namespace]/[resourcePath]?[loaders]";
  15. this.namespace = options.namespace || "";
  16. }
  17. apply(moduleTemplate) {
  18. moduleTemplate.hooks.module.tap(
  19. "EvalDevToolModuleTemplatePlugin",
  20. (source, module) => {
  21. const cacheEntry = cache.get(source);
  22. if (cacheEntry !== undefined) return cacheEntry;
  23. const content = source.source();
  24. const str = ModuleFilenameHelpers.createFilename(
  25. module,
  26. {
  27. moduleFilenameTemplate: this.moduleFilenameTemplate,
  28. namespace: this.namespace
  29. },
  30. moduleTemplate.runtimeTemplate.requestShortener
  31. );
  32. const footer =
  33. "\n" +
  34. this.sourceUrlComment.replace(
  35. /\[url\]/g,
  36. encodeURI(str)
  37. .replace(/%2F/g, "/")
  38. .replace(/%20/g, "_")
  39. .replace(/%5E/g, "^")
  40. .replace(/%5C/g, "\\")
  41. .replace(/^\//, "")
  42. );
  43. const result = new RawSource(
  44. `eval(${JSON.stringify(content + footer)});`
  45. );
  46. cache.set(source, result);
  47. return result;
  48. }
  49. );
  50. moduleTemplate.hooks.hash.tap("EvalDevToolModuleTemplatePlugin", hash => {
  51. hash.update("EvalDevToolModuleTemplatePlugin");
  52. hash.update("2");
  53. });
  54. }
  55. }
  56. module.exports = EvalDevToolModuleTemplatePlugin;