webpack/lib/LoaderOptionsPlugin.js

89 lines
2.3 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 23:08:51 +08:00
"use strict";
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
2018-11-12 16:15:06 +08:00
const NormalModule = require("./NormalModule");
const createSchemaValidation = require("./util/create-schema-validation");
2017-10-28 05:23:38 +08:00
/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */
2018-11-09 05:59:19 +08:00
/** @typedef {import("./Compiler")} Compiler */
2025-04-04 21:38:51 +08:00
/** @typedef {import("./ModuleFilenameHelpers").Matcher} Matcher */
/** @typedef {import("./ModuleFilenameHelpers").MatchObject} MatchObject */
2025-04-04 21:38:51 +08:00
/**
* @template T
* @typedef {import("../declarations/LoaderContext").LoaderContext<T>} LoaderContext
*/
const validate = createSchemaValidation(
require("../schemas/plugins/LoaderOptionsPlugin.check.js"),
() => require("../schemas/plugins/LoaderOptionsPlugin.json"),
{
name: "Loader Options Plugin",
baseDataPath: "options"
}
);
2025-04-23 20:03:37 +08:00
const PLUGIN_NAME = "LoaderOptionsPlugin";
class LoaderOptionsPlugin {
/**
* @param {LoaderOptionsPluginOptions & MatchObject} options options object
*/
2019-08-07 21:55:03 +08:00
constructor(options = {}) {
validate(options);
// If no options are set then generate empty options object
2018-02-25 09:00:20 +08:00
if (typeof options !== "object") options = {};
if (!options.test) {
2025-04-04 21:38:51 +08:00
/** @type {TODO} */
const defaultTrueMockRegExp = {
2018-02-25 09:00:20 +08:00
test: () => true
};
/** @type {RegExp} */
options.test = defaultTrueMockRegExp;
}
this.options = options;
}
2018-11-09 05:59:19 +08:00
/**
2020-04-23 16:48:36 +08:00
* Apply the plugin
2018-11-09 05:59:19 +08:00
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const options = this.options;
2025-04-23 20:03:37 +08:00
compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
2018-11-12 21:13:55 +08:00
NormalModule.getCompilationHooks(compilation).loader.tap(
2025-04-23 20:03:37 +08:00
PLUGIN_NAME,
2018-11-12 21:13:55 +08:00
(context, module) => {
2018-02-25 09:00:20 +08:00
const resource = module.resource;
if (!resource) return;
const i = resource.indexOf("?");
if (
ModuleFilenameHelpers.matchObject(
options,
i < 0 ? resource : resource.slice(0, i)
2018-02-25 09:00:20 +08:00
)
) {
for (const key of Object.keys(options)) {
if (key === "include" || key === "exclude" || key === "test") {
continue;
}
2024-10-24 11:02:20 +08:00
2025-03-27 08:07:25 +08:00
/** @type {TODO} */
2024-10-24 11:02:20 +08:00
(context)[key] = options[key];
2018-01-22 20:52:43 +08:00
}
}
}
2018-02-25 09:00:20 +08:00
);
});
}
}
module.exports = LoaderOptionsPlugin;