-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrewriteRelativeImportExtensionsPlugin.ts
49 lines (41 loc) · 1.5 KB
/
rewriteRelativeImportExtensionsPlugin.ts
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
import fs from "node:fs";
import path from "node:path";
import type { Plugin, PluginBuild } from "esbuild";
import { rewriteRelativeImportExtension } from "./rewriteRelativeImportExtension.ts";
export interface RewriteRelativeImportPluginExtensionsOptions {
/** If set to `true` paths ending with `.tsx` and `.jsx` will be `.jsx` instead. */
preserveJsx?: boolean;
}
/** Please see https://github.com/evanw/esbuild/issues/2435 */
export function rewriteRelativeImportExtensionsPlugin(
options: RewriteRelativeImportPluginExtensionsOptions = {},
): Plugin {
return {
name: "rewrite-relative-import-extensions",
setup(build: PluginBuild) {
const write = build.initialOptions.write;
build.initialOptions.write = false;
build.onEnd((result) => {
const files = result.outputFiles ?? [];
for (const file of files) {
let output = file.text;
const matches = output.matchAll(
/(?<=(?:import|export\s*[*{])[^"']+["'])([^"']+)(?=["'])/g,
);
for (const match of matches) {
output = output.replaceAll(match[0], (m, index) => {
if (match.index !== index) {
return m;
}
return rewriteRelativeImportExtension(m, options.preserveJsx);
});
}
if (write === undefined || write) {
fs.mkdirSync(path.dirname(file.path), { recursive: true });
fs.writeFileSync(file.path, output);
}
}
});
},
};
}