JsonModulesPlugin.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. apply(compiler) {
  32. compiler.hooks.compilation.tap(
  33. PLUGIN_NAME,
  34. (compilation, { normalModuleFactory }) => {
  35. normalModuleFactory.hooks.createParser
  36. .for(JSON_MODULE_TYPE)
  37. .tap(PLUGIN_NAME, parserOptions => {
  38. validate(parserOptions);
  39. return new JsonParser(parserOptions);
  40. });
  41. normalModuleFactory.hooks.createGenerator
  42. .for(JSON_MODULE_TYPE)
  43. .tap(PLUGIN_NAME, () => new JsonGenerator());
  44. }
  45. );
  46. }
  47. }
  48. module.exports = JsonModulesPlugin;