Created
November 6, 2023 16:52
-
-
Save maximilianschmitt/84897ae503fa2089fc6bbd928543b97d to your computer and use it in GitHub Desktop.
Rewrite absolute TypeScript paths to relative ones
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const path = require("path"); | |
const srcDir = path.join(__dirname, "src"); | |
// Define the absolute paths to replace and their corresponding relative paths | |
const patterns = { | |
"@pages/": "./src/pages/", | |
"@lib/": "./src/", | |
"@components/": "./src/components/", | |
"@models/": "./src/models/", | |
"@public/": "./src/public/", | |
}; | |
const regexes = Object.keys(patterns).map((pattern) => { | |
return new RegExp(`(${pattern})`, "g"); | |
}); | |
// Recursively find all .ts and .tsx files in the src/ directory | |
const findFiles = (dir, fileList = []) => { | |
const files = fs.readdirSync(dir); | |
files.forEach((file) => { | |
const filePath = path.join(dir, file); | |
if (fs.statSync(filePath).isDirectory()) { | |
findFiles(filePath, fileList); | |
} else if (/\.(ts|tsx)$/.test(filePath)) { | |
fileList.push(filePath); | |
} | |
}); | |
return fileList; | |
}; | |
// Replace the absolute paths with the corresponding relative paths in each file | |
const replacePaths = (file) => { | |
let content = fs.readFileSync(file, "utf8"); | |
console.log(file); | |
for (const regex of regexes) { | |
content = content.replace(regex, (match) => { | |
console.log( | |
">>", | |
match, | |
path.relative(path.dirname(file), patterns[match]), | |
); | |
return path.relative(path.dirname(file), patterns[match]) + "/"; | |
}); | |
} | |
fs.writeFileSync(file, content, "utf8"); | |
}; | |
// Find all .ts and .tsx files in the src/ directory and replace the absolute paths with relative ones | |
const files = findFiles(srcDir); | |
files.forEach((file) => replacePaths(file)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment