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 {function(TODO): void} ModuleReplacer */
|
---|
12 |
|
---|
13 | class NormalModuleReplacementPlugin {
|
---|
14 | /**
|
---|
15 | * Create an instance of the plugin
|
---|
16 | * @param {RegExp} resourceRegExp the resource matcher
|
---|
17 | * @param {string|ModuleReplacer} newResource the resource replacement
|
---|
18 | */
|
---|
19 | constructor(resourceRegExp, newResource) {
|
---|
20 | this.resourceRegExp = resourceRegExp;
|
---|
21 | this.newResource = newResource;
|
---|
22 | }
|
---|
23 |
|
---|
24 | /**
|
---|
25 | * Apply the plugin
|
---|
26 | * @param {Compiler} compiler the compiler instance
|
---|
27 | * @returns {void}
|
---|
28 | */
|
---|
29 | apply(compiler) {
|
---|
30 | const resourceRegExp = this.resourceRegExp;
|
---|
31 | const newResource = this.newResource;
|
---|
32 | compiler.hooks.normalModuleFactory.tap(
|
---|
33 | "NormalModuleReplacementPlugin",
|
---|
34 | nmf => {
|
---|
35 | nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => {
|
---|
36 | if (resourceRegExp.test(result.request)) {
|
---|
37 | if (typeof newResource === "function") {
|
---|
38 | newResource(result);
|
---|
39 | } else {
|
---|
40 | result.request = newResource;
|
---|
41 | }
|
---|
42 | }
|
---|
43 | });
|
---|
44 | nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => {
|
---|
45 | const createData = result.createData;
|
---|
46 | if (resourceRegExp.test(createData.resource)) {
|
---|
47 | if (typeof newResource === "function") {
|
---|
48 | newResource(result);
|
---|
49 | } else {
|
---|
50 | const fs = compiler.inputFileSystem;
|
---|
51 | if (
|
---|
52 | newResource.startsWith("/") ||
|
---|
53 | (newResource.length > 1 && newResource[1] === ":")
|
---|
54 | ) {
|
---|
55 | createData.resource = newResource;
|
---|
56 | } else {
|
---|
57 | createData.resource = join(
|
---|
58 | fs,
|
---|
59 | dirname(fs, createData.resource),
|
---|
60 | newResource
|
---|
61 | );
|
---|
62 | }
|
---|
63 | }
|
---|
64 | }
|
---|
65 | });
|
---|
66 | }
|
---|
67 | );
|
---|
68 | }
|
---|
69 | }
|
---|
70 |
|
---|
71 | module.exports = NormalModuleReplacementPlugin;
|
---|