Created
February 23, 2024 11:11
-
-
Save danew/f7ff66bb51c12be6af9410e1bc96acc8 to your computer and use it in GitHub Desktop.
A quick script to replace all the alias module imports with relative imports.
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
import ts from 'typescript'; | |
import fs from 'fs'; | |
import path from 'path'; | |
const projectRoot = process.cwd(); | |
const tsConfigPath = path.join(projectRoot, 'tsconfig.json'); | |
const tsConfig = ts.readConfigFile(tsConfigPath, ts.sys.readFile).config; | |
const parsedTsConfig = ts.parseJsonConfigFileContent(tsConfig, ts.sys, projectRoot); | |
function resolvePath(from: string, to: string): string { | |
const resolvedPath = path.relative(path.dirname(from), to); | |
return resolvedPath.startsWith('.') ? resolvedPath : `./${resolvedPath}`; | |
} | |
function replacePathsInFile(filePath: string) { | |
let fileContent = fs.readFileSync(filePath, 'utf8'); | |
const regex = /from\s+['"]~\/(.*?)['"]/g; | |
fileContent = fileContent.replace(regex, (match, p1) => { | |
const absolutePath = path.join(parsedTsConfig.options.baseUrl || '', 'src', p1); | |
const relativePath = resolvePath(filePath, absolutePath); | |
return `from '${relativePath}'`; | |
}); | |
fs.writeFileSync(filePath, fileContent, 'utf8'); | |
} | |
parsedTsConfig.fileNames.forEach((file) => { | |
replacePathsInFile(file); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This assumes that the alias is
"~/*": ["./src/*"]