LoaderOptionsPlugin.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. class LoaderOptionsPlugin {
  26. /**
  27. * @param {LoaderOptionsPluginOptions & MatchObject} options options object
  28. */
  29. constructor(options = {}) {
  30. validate(options);
  31. // If no options are set then generate empty options object
  32. if (typeof options !== "object") options = {};
  33. if (!options.test) {
  34. /** @type {TODO} */
  35. const defaultTrueMockRegExp = {
  36. test: () => true
  37. };
  38. /** @type {RegExp} */
  39. options.test = defaultTrueMockRegExp;
  40. }
  41. this.options = options;
  42. }
  43. /**
  44. * Apply the plugin
  45. * @param {Compiler} compiler the compiler instance
  46. * @returns {void}
  47. */
  48. apply(compiler) {
  49. const options = this.options;
  50. compiler.hooks.compilation.tap("LoaderOptionsPlugin", compilation => {
  51. NormalModule.getCompilationHooks(compilation).loader.tap(
  52. "LoaderOptionsPlugin",
  53. (context, module) => {
  54. const resource = module.resource;
  55. if (!resource) return;
  56. const i = resource.indexOf("?");
  57. if (
  58. ModuleFilenameHelpers.matchObject(
  59. options,
  60. i < 0 ? resource : resource.slice(0, i)
  61. )
  62. ) {
  63. for (const key of Object.keys(options)) {
  64. if (key === "include" || key === "exclude" || key === "test") {
  65. continue;
  66. }
  67. /** @type {TODO} */
  68. (context)[key] = options[key];
  69. }
  70. }
  71. }
  72. );
  73. });
  74. }
  75. }
  76. module.exports = LoaderOptionsPlugin;