-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.paths.ts
53 lines (45 loc) · 1.35 KB
/
build.paths.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
50
51
52
53
import fs from "fs-extra";
import path from "pathe";
const distDir = path.resolve(__dirname, "dist");
function replaceImportPaths(
content: string,
fileDir: string,
rootDir: string,
): string {
return content.replace(
/(from\s+['"])~(\/[^'"]*)(['"])/g,
(match, prefix, importPath, suffix) => {
const relativePathToRoot = path.relative(fileDir, rootDir) || ".";
let newPath = path.join(relativePathToRoot, importPath);
newPath = newPath.replace(/\\/g, "/");
if (!newPath.startsWith(".")) {
newPath = `./${newPath}`;
}
return `${prefix}${newPath}${suffix}`;
},
);
}
async function processFiles(dir: string) {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
await processFiles(filePath);
} else if (filePath.endsWith(".js") || filePath.endsWith(".d.ts")) {
const content = fs.readFileSync(filePath, "utf8");
const updatedContent = replaceImportPaths(
content,
path.dirname(filePath),
distDir,
);
if (content !== updatedContent) {
fs.writeFileSync(filePath, updatedContent, "utf8");
}
}
}
}
processFiles(distDir).catch((error) => {
console.error("An error occurred:", error);
process.exit(1);
});