JsonModulesPlugin.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { JSON_MODULE_TYPE } = require("../ModuleTypeConstants");
  7. const createSchemaValidation = require("../util/create-schema-validation");
  8. const JsonGenerator = require("./JsonGenerator");
  9. const JsonParser = require("./JsonParser");
  10. /** @typedef {import("../Compiler")} Compiler */
  11. /** @typedef {Record<string, any>} RawJsonData */
  12. const validate = createSchemaValidation(
  13. require("../../schemas/plugins/JsonModulesPluginParser.check.js"),
  14. () => require("../../schemas/plugins/JsonModulesPluginParser.json"),
  15. {
  16. name: "Json Modules Plugin",
  17. baseDataPath: "parser"
  18. }
  19. );
  20. const PLUGIN_NAME = "JsonModulesPlugin";
  21. /**
  22. * The JsonModulesPlugin is the entrypoint plugin for the json modules feature.
  23. * It adds the json module type to the compiler and registers the json parser and generator.
  24. */
  25. class JsonModulesPlugin {
  26. /**
  27. * Apply the plugin
  28. * @param {Compiler} compiler the compiler instance
  29. * @returns {void}
  30. *
  31. */
  32. apply(compiler) {
  33. compiler.hooks.compilation.tap(
  34. PLUGIN_NAME,
  35. (compilation, { normalModuleFactory }) => {
  36. normalModuleFactory.hooks.createParser
  37. .for(JSON_MODULE_TYPE)
  38. .tap(PLUGIN_NAME, parserOptions => {
  39. validate(parserOptions);
  40. return new JsonParser(parserOptions);
  41. });
  42. normalModuleFactory.hooks.createGenerator
  43. .for(JSON_MODULE_TYPE)
  44. .tap(PLUGIN_NAME, () => {
  45. return new JsonGenerator();
  46. });
  47. }
  48. );
  49. }
  50. }
  51. module.exports = JsonModulesPlugin;