UNPKG

1.5 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5"use strict";
6
7const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
8
9const validateOptions = require("schema-utils");
10const schema = require("../schemas/plugins/LoaderOptionsPlugin.json");
11
12/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */
13
14class LoaderOptionsPlugin {
15 /**
16 * @param {LoaderOptionsPluginOptions} options options object
17 */
18 constructor(options) {
19 validateOptions(schema, options || {}, "Loader Options Plugin");
20
21 if (typeof options !== "object") options = {};
22 if (!options.test) {
23 options.test = {
24 test: () => true
25 };
26 }
27 this.options = options;
28 }
29
30 apply(compiler) {
31 const options = this.options;
32 compiler.hooks.compilation.tap("LoaderOptionsPlugin", compilation => {
33 compilation.hooks.normalModuleLoader.tap(
34 "LoaderOptionsPlugin",
35 (context, module) => {
36 const resource = module.resource;
37 if (!resource) return;
38 const i = resource.indexOf("?");
39 if (
40 ModuleFilenameHelpers.matchObject(
41 options,
42 i < 0 ? resource : resource.substr(0, i)
43 )
44 ) {
45 for (const key of Object.keys(options)) {
46 if (key === "include" || key === "exclude" || key === "test") {
47 continue;
48 }
49 context[key] = options[key];
50 }
51 }
52 }
53 );
54 });
55 }
56}
57
58module.exports = LoaderOptionsPlugin;