UNPKG

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