1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | Author Tobias Koppers @sokra
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | const { join, dirname } = require("./util/fs");
|
---|
9 |
|
---|
10 | /** @typedef {import("./Compiler")} Compiler */
|
---|
11 | /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
|
---|
12 |
|
---|
13 | /** @typedef {function(import("./NormalModuleFactory").ResolveData): void} ModuleReplacer */
|
---|
14 |
|
---|
15 | class NormalModuleReplacementPlugin {
|
---|
16 | /**
|
---|
17 | * Create an instance of the plugin
|
---|
18 | * @param {RegExp} resourceRegExp the resource matcher
|
---|
19 | * @param {string|ModuleReplacer} newResource the resource replacement
|
---|
20 | */
|
---|
21 | constructor(resourceRegExp, newResource) {
|
---|
22 | this.resourceRegExp = resourceRegExp;
|
---|
23 | this.newResource = newResource;
|
---|
24 | }
|
---|
25 |
|
---|
26 | /**
|
---|
27 | * Apply the plugin
|
---|
28 | * @param {Compiler} compiler the compiler instance
|
---|
29 | * @returns {void}
|
---|
30 | */
|
---|
31 | apply(compiler) {
|
---|
32 | const resourceRegExp = this.resourceRegExp;
|
---|
33 | const newResource = this.newResource;
|
---|
34 | compiler.hooks.normalModuleFactory.tap(
|
---|
35 | "NormalModuleReplacementPlugin",
|
---|
36 | nmf => {
|
---|
37 | nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => {
|
---|
38 | if (resourceRegExp.test(result.request)) {
|
---|
39 | if (typeof newResource === "function") {
|
---|
40 | newResource(result);
|
---|
41 | } else {
|
---|
42 | result.request = newResource;
|
---|
43 | }
|
---|
44 | }
|
---|
45 | });
|
---|
46 | nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => {
|
---|
47 | const createData = result.createData;
|
---|
48 | if (
|
---|
49 | resourceRegExp.test(/** @type {string} */ (createData.resource))
|
---|
50 | ) {
|
---|
51 | if (typeof newResource === "function") {
|
---|
52 | newResource(result);
|
---|
53 | } else {
|
---|
54 | const fs =
|
---|
55 | /** @type {InputFileSystem} */
|
---|
56 | (compiler.inputFileSystem);
|
---|
57 | if (
|
---|
58 | newResource.startsWith("/") ||
|
---|
59 | (newResource.length > 1 && newResource[1] === ":")
|
---|
60 | ) {
|
---|
61 | createData.resource = newResource;
|
---|
62 | } else {
|
---|
63 | createData.resource = join(
|
---|
64 | fs,
|
---|
65 | dirname(fs, /** @type {string} */ (createData.resource)),
|
---|
66 | newResource
|
---|
67 | );
|
---|
68 | }
|
---|
69 | }
|
---|
70 | }
|
---|
71 | });
|
---|
72 | }
|
---|
73 | );
|
---|
74 | }
|
---|
75 | }
|
---|
76 |
|
---|
77 | module.exports = NormalModuleReplacementPlugin;
|
---|