-
-
Notifications
You must be signed in to change notification settings - Fork 5k
Expand file tree
/
Copy pathreplace-module.mjs
More file actions
62 lines (52 loc) · 1.67 KB
/
Copy pathreplace-module.mjs
File metadata and controls
62 lines (52 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
export default function esbuildPluginReplaceModule(replacements = {}) {
const pathReplacements = new Map();
const contentsReplacements = new Map();
for (let [file, options] of Object.entries(replacements)) {
if (typeof options === "string") {
options = { path: options };
}
if (Reflect.has(options, "path")) {
pathReplacements.set(file, options);
continue;
}
if (Reflect.has(options, "contents")) {
contentsReplacements.set(file, options);
continue;
}
throw new Error("'path' or 'contents' is required.");
}
return {
name: "replace-module",
setup(build) {
// `build.resolve()` will call `onResolve` listener
// Avoid infinite loop
const seen = new Set();
build.onResolve({ filter: /./ }, async (args) => {
if (
!(args.kind === "require-call" || args.kind === "import-statement") ||
args.namespace !== "file"
) {
return;
}
const key = JSON.stringify(args);
if (seen.has(key)) {
return;
}
seen.add(key);
const resolveResult = await build.resolve(args.path, {
importer: args.importer,
namespace: args.namespace,
resolveDir: args.resolveDir,
kind: args.kind,
pluginData: args.pluginData,
});
// `build.resolve()` seems not respecting `browser` field in `package.json`
// Return `undefined` instead of `resolveResult` so esbuild can resolve correctly
return pathReplacements.get(resolveResult.path);
});
build.onLoad({ filter: /./ }, ({ path }) =>
contentsReplacements.get(path)
);
},
};
}