LoaderOptionsPlugin.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. const validate = createSchemaValidation(
  12. require("../schemas/plugins/LoaderOptionsPlugin.check.js"),
  13. () => require("../schemas/plugins/LoaderOptionsPlugin.json"),
  14. {
  15. name: "Loader Options Plugin",
  16. baseDataPath: "options"
  17. }
  18. );
  19. class LoaderOptionsPlugin {
  20. /**
  21. * @param {LoaderOptionsPluginOptions} options options object
  22. */
  23. constructor(options = {}) {
  24. validate(options);
  25. if (typeof options !== "object") options = {};
  26. if (!options.test) {
  27. options.test = {
  28. test: () => true
  29. };
  30. }
  31. this.options = options;
  32. }
  33. /**
  34. * Apply the plugin
  35. * @param {Compiler} compiler the compiler instance
  36. * @returns {void}
  37. */
  38. apply(compiler) {
  39. const options = this.options;
  40. compiler.hooks.compilation.tap("LoaderOptionsPlugin", compilation => {
  41. NormalModule.getCompilationHooks(compilation).loader.tap(
  42. "LoaderOptionsPlugin",
  43. (context, module) => {
  44. const resource = module.resource;
  45. if (!resource) return;
  46. const i = resource.indexOf("?");
  47. if (
  48. ModuleFilenameHelpers.matchObject(
  49. options,
  50. i < 0 ? resource : resource.slice(0, i)
  51. )
  52. ) {
  53. for (const key of Object.keys(options)) {
  54. if (key === "include" || key === "exclude" || key === "test") {
  55. continue;
  56. }
  57. context[key] = options[key];
  58. }
  59. }
  60. }
  61. );
  62. });
  63. }
  64. }
  65. module.exports = LoaderOptionsPlugin;