JsonModulesPlugin.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 {import("../util/fs").JsonArray} JsonArray */
  12. /** @typedef {import("../util/fs").JsonObject} JsonObject */
  13. /** @typedef {import("../util/fs").JsonValue} JsonValue */
  14. const validate = createSchemaValidation(
  15. require("../../schemas/plugins/json/JsonModulesPluginParser.check.js"),
  16. () => require("../../schemas/plugins/json/JsonModulesPluginParser.json"),
  17. {
  18. name: "Json Modules Plugin",
  19. baseDataPath: "parser"
  20. }
  21. );
  22. const validateGenerator = createSchemaValidation(
  23. require("../../schemas/plugins/json/JsonModulesPluginGenerator.check.js"),
  24. () => require("../../schemas/plugins/json/JsonModulesPluginGenerator.json"),
  25. {
  26. name: "Json Modules Plugin",
  27. baseDataPath: "generator"
  28. }
  29. );
  30. const PLUGIN_NAME = "JsonModulesPlugin";
  31. /**
  32. * The JsonModulesPlugin is the entrypoint plugin for the json modules feature.
  33. * It adds the json module type to the compiler and registers the json parser and generator.
  34. */
  35. class JsonModulesPlugin {
  36. /**
  37. * Apply the plugin
  38. * @param {Compiler} compiler the compiler instance
  39. * @returns {void}
  40. */
  41. apply(compiler) {
  42. compiler.hooks.compilation.tap(
  43. PLUGIN_NAME,
  44. (compilation, { normalModuleFactory }) => {
  45. normalModuleFactory.hooks.createParser
  46. .for(JSON_MODULE_TYPE)
  47. .tap(PLUGIN_NAME, parserOptions => {
  48. validate(parserOptions);
  49. return new JsonParser(parserOptions);
  50. });
  51. normalModuleFactory.hooks.createGenerator
  52. .for(JSON_MODULE_TYPE)
  53. .tap(PLUGIN_NAME, generatorOptions => {
  54. validateGenerator(generatorOptions);
  55. return new JsonGenerator(generatorOptions);
  56. });
  57. }
  58. );
  59. }
  60. }
  61. module.exports = JsonModulesPlugin;