webpack/lib/LoaderOptionsPlugin.js

69 lines
1.7 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");
2020-10-06 02:41:45 +08:00
const { validate } = require("schema-utils");
const schema = require("../schemas/plugins/LoaderOptionsPlugin.json");
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 */
class LoaderOptionsPlugin {
/**
* @param {LoaderOptionsPluginOptions} options options object
*/
2019-08-07 21:55:03 +08:00
constructor(options = {}) {
2020-10-06 02:41:45 +08:00
validate(schema, options, {
2019-08-07 21:55:03 +08:00
name: "Loader Options Plugin",
baseDataPath: "options"
});
2018-02-25 09:00:20 +08:00
if (typeof options !== "object") options = {};
if (!options.test) {
2018-02-25 09:00:20 +08:00
options.test = {
test: () => true
};
}
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;
2018-02-25 09:00:20 +08:00
compiler.hooks.compilation.tap("LoaderOptionsPlugin", compilation => {
2018-11-12 21:13:55 +08:00
NormalModule.getCompilationHooks(compilation).loader.tap(
2018-02-25 09:00:20 +08:00
"LoaderOptionsPlugin",
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.substr(0, i)
)
) {
for (const key of Object.keys(options)) {
if (key === "include" || key === "exclude" || key === "test") {
continue;
}
context[key] = options[key];
2018-01-22 20:52:43 +08:00
}
}
}
2018-02-25 09:00:20 +08:00
);
});
}
}
module.exports = LoaderOptionsPlugin;