LoaderOptionsPlugin.js 1.3 KB

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