UNPKG

2.81 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 validateOptions = require("schema-utils");
8const schema = require("../schemas/plugins/IgnorePlugin.json");
9
10/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */
11/** @typedef {import("./Compiler")} Compiler */
12
13class IgnorePlugin {
14 /**
15 * @param {IgnorePluginOptions} options IgnorePlugin options
16 */
17 constructor(options) {
18 // TODO webpack 5 remove this compat-layer
19 if (arguments.length > 1 || options instanceof RegExp) {
20 options = {
21 resourceRegExp: arguments[0],
22 contextRegExp: arguments[1]
23 };
24 }
25
26 validateOptions(schema, options, "IgnorePlugin");
27 this.options = options;
28
29 /** @private @type {Function} */
30 this.checkIgnore = this.checkIgnore.bind(this);
31 }
32
33 /**
34 * @param {string} resource resource
35 * @returns {boolean} returns true if a "resourceRegExp" exists
36 * and the resource given matches the regexp.
37 */
38 checkResource(resource) {
39 if ("checkResource" in this.options && this.options.checkResource) {
40 return this.options.checkResource(resource);
41 }
42 if ("resourceRegExp" in this.options && this.options.resourceRegExp) {
43 return this.options.resourceRegExp.test(resource);
44 }
45 return false;
46 }
47
48 /**
49 * @param {string} context context
50 * @returns {boolean} returns true if "contextRegExp" does not exist
51 * or if context matches the given regexp.
52 */
53 checkContext(context) {
54 if ("checkContext" in this.options && this.options.checkContext) {
55 return this.options.checkContext(context);
56 }
57 if ("contextRegExp" in this.options && this.options.contextRegExp) {
58 return this.options.contextRegExp.test(context);
59 }
60 return true;
61 }
62
63 /**
64 * Note that if "contextRegExp" is given, both the "resourceRegExp"
65 * and "contextRegExp" have to match.
66 *
67 * @param {TODO} result result
68 * @returns {boolean} returns true if result should be ignored
69 */
70 checkResult(result) {
71 if (!result) {
72 return true;
73 }
74 return (
75 this.checkResource(result.request) && this.checkContext(result.context)
76 );
77 }
78
79 /**
80 * @param {TODO} result result
81 * @returns {TODO|null} returns result or null if result should be ignored
82 */
83 checkIgnore(result) {
84 // check if result is ignored
85 if (this.checkResult(result)) {
86 return null;
87 }
88 return result;
89 }
90
91 /**
92 * @param {Compiler} compiler Webpack Compiler
93 * @returns {void}
94 */
95 apply(compiler) {
96 compiler.hooks.normalModuleFactory.tap("IgnorePlugin", nmf => {
97 nmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
98 });
99 compiler.hooks.contextModuleFactory.tap("IgnorePlugin", cmf => {
100 cmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
101 });
102 }
103}
104
105module.exports = IgnorePlugin;