UNPKG

2.43 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 * Note that if "contextRegExp" is given, both the "resourceRegExp"
35 * and "contextRegExp" have to match.
36 *
37 * @param {TODO} result result
38 * @returns {TODO|null} returns result or null if result should be ignored
39 */
40 checkIgnore(result) {
41 if (!result) return result;
42
43 if (
44 "checkResource" in this.options &&
45 this.options.checkResource &&
46 this.options.checkResource(result.request, result.context)
47 ) {
48 // TODO webpack 5 remove checkContext, as checkResource already gets context
49 if ("checkContext" in this.options && this.options.checkContext) {
50 if (this.options.checkContext(result.context)) {
51 return null;
52 }
53 } else {
54 return null;
55 }
56 }
57
58 if (
59 "resourceRegExp" in this.options &&
60 this.options.resourceRegExp &&
61 this.options.resourceRegExp.test(result.request)
62 ) {
63 if ("contextRegExp" in this.options && this.options.contextRegExp) {
64 // if "contextRegExp" is given,
65 // both the "resourceRegExp" and "contextRegExp" have to match.
66 if (this.options.contextRegExp.test(result.context)) {
67 return null;
68 }
69 } else {
70 return null;
71 }
72 }
73
74 return result;
75 }
76
77 /**
78 * @param {Compiler} compiler Webpack Compiler
79 * @returns {void}
80 */
81 apply(compiler) {
82 compiler.hooks.normalModuleFactory.tap("IgnorePlugin", nmf => {
83 nmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
84 });
85 compiler.hooks.contextModuleFactory.tap("IgnorePlugin", cmf => {
86 cmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
87 });
88 }
89}
90
91module.exports = IgnorePlugin;