UNPKG

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