You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.5 KiB

4 years ago
  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;