-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfix-imports.js
46 lines (36 loc) · 1.51 KB
/
fix-imports.js
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
import { readdirSync, statSync, readFileSync, existsSync, writeFileSync } from "fs";
import { join, resolve, dirname } from "path";
const directory = "./dist"; // Adjust this if your output directory differs
function fixImports(dir) {
const files = readdirSync(dir);
files.forEach((file) => {
const fullPath = join(dir, file);
if (statSync(fullPath).isDirectory()) {
fixImports(fullPath); // Recursively process subdirectories
} else if (file.endsWith(".js")) {
let content = readFileSync(fullPath, "utf-8");
// Match import paths without extensions or pointing to folders
const updatedContent = content.replace(
/from\s+["'](\..*?)["']/g,
(match, importPath) => {
const resolvedPath = resolve(dirname(fullPath), importPath);
if (importPath === ".") {
// Special case: import "." -> import "./index.js"
return `from "./index.js"`;
} else if (existsSync(`${resolvedPath}.js`)) {
// If the path resolves to a .js file
return `from "${importPath}.js"`;
} else if (existsSync(resolvedPath) && statSync(resolvedPath).isDirectory()) {
// If the path resolves to a directory
return `from "${importPath}/index.js"`;
}
// If the path doesn't resolve, leave it unchanged
return match;
}
);
writeFileSync(fullPath, updatedContent, "utf-8");
console.log(`Fixed imports in: ${fullPath}`);
}
});
}
fixImports(directory);