-
Notifications
You must be signed in to change notification settings - Fork 0
/
correctImports.mjs
52 lines (44 loc) · 1.64 KB
/
correctImports.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
49
50
51
52
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
// Helper function to convert `__dirname` in ES modules
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
// Function to read all files in a directory recursively
function getAllFiles(dir, fileList = []) {
for (const file of fs.readdirSync(dir)) {
const filePath = path.join(dir, file)
if (fs.lstatSync(filePath).isDirectory()) {
getAllFiles(filePath, fileList)
} else if (path.extname(file) === '.ts') {
fileList.push(filePath)
}
}
return fileList
}
// Function to process imports and exports in a file
function processImportsExports(filePath) {
let content = fs.readFileSync(filePath, 'utf8')
const regex = /(import|export)\s+(.*?from\s+["'])(\.{1,2}\/.*?)(["'])/g
content = content.replaceAll(regex, (match, p1, p2, p3, p4) => {
const resolvedPath = path.resolve(path.dirname(filePath), p3)
if (fs.existsSync(resolvedPath) && fs.lstatSync(resolvedPath).isDirectory()) {
return `${p1} ${p2}${p3}/index.js${p4}`
} else if (!/\.(json|js|ts|jsx|tsx)$/.test(p3)) {
return `${p1} ${p2}${p3}.js${p4}`
}
return match
})
fs.writeFileSync(filePath, content, 'utf8')
}
// Main function to process all .ts files in the directory
function processFiles(directoryPath) {
const files = getAllFiles(directoryPath)
for (const filePath of files) {
processImportsExports(filePath)
}
}
// Change this to your source directory
const directoryPath = path.join(__dirname, 'packages')
processFiles(directoryPath)
console.log('Import paths corrected successfully.')