Generator.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("./NormalModule")} NormalModule */
  7. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  8. /** @typedef {import("webpack-sources").Source} Source */
  9. /** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */
  10. /**
  11. *
  12. */
  13. class Generator {
  14. static byType(map) {
  15. return new ByTypeGenerator(map);
  16. }
  17. /**
  18. * @abstract
  19. * @param {NormalModule} module module for which the code should be generated
  20. * @param {Map<Function, DependencyTemplate>} dependencyTemplates mapping from dependencies to templates
  21. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  22. * @param {string} type which kind of code should be generated
  23. * @returns {Source} generated code
  24. */
  25. generate(module, dependencyTemplates, runtimeTemplate, type) {
  26. throw new Error("Generator.generate: must be overridden");
  27. }
  28. }
  29. class ByTypeGenerator extends Generator {
  30. constructor(map) {
  31. super();
  32. this.map = map;
  33. }
  34. /**
  35. * @param {NormalModule} module module for which the code should be generated
  36. * @param {Map<Function, DependencyTemplate>} dependencyTemplates mapping from dependencies to templates
  37. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  38. * @param {string} type which kind of code should be generated
  39. * @returns {Source} generated code
  40. */
  41. generate(module, dependencyTemplates, runtimeTemplate, type) {
  42. const generator = this.map[type];
  43. if (!generator) {
  44. throw new Error(`Generator.byType: no generator specified for ${type}`);
  45. }
  46. return generator.generate(
  47. module,
  48. dependencyTemplates,
  49. runtimeTemplate,
  50. type
  51. );
  52. }
  53. }
  54. module.exports = Generator;