forked from prettier/prettier
/
replace-text.mjs
48 lines (40 loc) · 1.24 KB
/
replace-text.mjs
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
import fs from "node:fs/promises";
export default function esbuildPluginReplaceText({
filter = /./,
replacements,
}) {
for (const replacement of replacements) {
if (!replacement.file) {
throw new Error("'file' option is required.");
}
if (Object.prototype.hasOwnProperty.call(replacement, "process")) {
if (typeof replacement.process !== "function") {
throw new TypeError("'process' option should be a function.");
}
continue;
}
if (
!Object.prototype.hasOwnProperty.call(replacement, "find") ||
!Object.prototype.hasOwnProperty.call(replacement, "replacement")
) {
throw new Error("'find' and 'replacement' option is required.");
}
replacement.process = (text) =>
text.replaceAll(replacement.find, replacement.replacement);
}
return {
name: "replace-text",
setup(build) {
build.onLoad({ filter }, async ({ path: file }) => {
let text = await fs.readFile(file, "utf8");
for (const replacement of replacements) {
if (replacement.file !== "*" && replacement.file !== file) {
continue;
}
text = replacement.process(text);
}
return { contents: text };
});
},
};
}