-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfix-imports.js
63 lines (48 loc) · 1.69 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// Get the directory name of the current module
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Function to recursively get all TypeScript files
function getTypeScriptFiles(dir, fileList = []) {
const files = fs.readdirSync(dir);
files.forEach(file => {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
getTypeScriptFiles(filePath, fileList);
} else if (file.endsWith('.ts') && !file.endsWith('.d.ts')) {
fileList.push(filePath);
}
});
return fileList;
}
// Function to fix imports in a file
function fixImportsInFile(filePath) {
console.log(`Processing ${filePath}`);
let content = fs.readFileSync(filePath, 'utf8');
// Regular expression to match relative imports without file extensions
const importRegex = /from\s+['"](\.[^'"]*)['"]/g;
// Replace imports to add .js extension
content = content.replace(importRegex, (match, importPath) => {
// Skip if the import already has an extension
if (importPath.endsWith('.js') || importPath.endsWith('.json')) {
return match;
}
return `from '${importPath}.js'`;
});
// Write the updated content back to the file
fs.writeFileSync(filePath, content, 'utf8');
}
// Main function
function main() {
const srcDir = path.join(__dirname, 'src');
const tsFiles = getTypeScriptFiles(srcDir);
console.log(`Found ${tsFiles.length} TypeScript files to process`);
tsFiles.forEach(filePath => {
fixImportsInFile(filePath);
});
console.log('All imports have been fixed!');
}
main();