LoaderOptionsPlugin.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 validateOptions = require("schema-utils");
  8. const schema = require("../schemas/plugins/LoaderOptionsPlugin.json");
  9. /** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */
  10. class LoaderOptionsPlugin {
  11. /**
  12. * @param {LoaderOptionsPluginOptions} options options object
  13. */
  14. constructor(options) {
  15. validateOptions(schema, options || {}, "Loader Options Plugin");
  16. if (typeof options !== "object") options = {};
  17. if (!options.test) {
  18. options.test = {
  19. test: () => true
  20. };
  21. }
  22. this.options = options;
  23. }
  24. apply(compiler) {
  25. const options = this.options;
  26. compiler.hooks.compilation.tap("LoaderOptionsPlugin", compilation => {
  27. compilation.hooks.normalModuleLoader.tap(
  28. "LoaderOptionsPlugin",
  29. (context, module) => {
  30. const resource = module.resource;
  31. if (!resource) return;
  32. const i = resource.indexOf("?");
  33. if (
  34. ModuleFilenameHelpers.matchObject(
  35. options,
  36. i < 0 ? resource : resource.substr(0, i)
  37. )
  38. ) {
  39. for (const key of Object.keys(options)) {
  40. if (key === "include" || key === "exclude" || key === "test") {
  41. continue;
  42. }
  43. context[key] = options[key];
  44. }
  45. }
  46. }
  47. );
  48. });
  49. }
  50. }
  51. module.exports = LoaderOptionsPlugin;