LoaderOptionsPlugin.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
  7. const NormalModule = require("./NormalModule");
  8. const createSchemaValidation = require("./util/create-schema-validation");
  9. /** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */
  10. /** @typedef {import("./Compiler")} Compiler */
  11. /** @typedef {import("./ModuleFilenameHelpers").Matcher} Matcher */
  12. /** @typedef {import("./ModuleFilenameHelpers").MatchObject} MatchObject */
  13. /**
  14. * @template T
  15. * @typedef {import("../declarations/LoaderContext").LoaderContext<T>} LoaderContext
  16. */
  17. const validate = createSchemaValidation(
  18. require("../schemas/plugins/LoaderOptionsPlugin.check.js"),
  19. () => require("../schemas/plugins/LoaderOptionsPlugin.json"),
  20. {
  21. name: "Loader Options Plugin",
  22. baseDataPath: "options"
  23. }
  24. );
  25. const PLUGIN_NAME = "LoaderOptionsPlugin";
  26. class LoaderOptionsPlugin {
  27. /**
  28. * @param {LoaderOptionsPluginOptions & MatchObject} options options object
  29. */
  30. constructor(options = {}) {
  31. validate(options);
  32. // If no options are set then generate empty options object
  33. if (typeof options !== "object") options = {};
  34. if (!options.test) {
  35. /** @type {TODO} */
  36. const defaultTrueMockRegExp = {
  37. test: () => true
  38. };
  39. /** @type {RegExp} */
  40. options.test = defaultTrueMockRegExp;
  41. }
  42. this.options = options;
  43. }
  44. /**
  45. * Apply the plugin
  46. * @param {Compiler} compiler the compiler instance
  47. * @returns {void}
  48. */
  49. apply(compiler) {
  50. const options = this.options;
  51. compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
  52. NormalModule.getCompilationHooks(compilation).loader.tap(
  53. PLUGIN_NAME,
  54. (context, module) => {
  55. const resource = module.resource;
  56. if (!resource) return;
  57. const i = resource.indexOf("?");
  58. if (
  59. ModuleFilenameHelpers.matchObject(
  60. options,
  61. i < 0 ? resource : resource.slice(0, i)
  62. )
  63. ) {
  64. for (const key of Object.keys(options)) {
  65. if (key === "include" || key === "exclude" || key === "test") {
  66. continue;
  67. }
  68. /** @type {TODO} */
  69. (context)[key] = options[key];
  70. }
  71. }
  72. }
  73. );
  74. });
  75. }
  76. }
  77. module.exports = LoaderOptionsPlugin;