Skip to content

Instantly share code, notes, and snippets.

@danew
Created February 23, 2024 11:11
Show Gist options
  • Save danew/f7ff66bb51c12be6af9410e1bc96acc8 to your computer and use it in GitHub Desktop.
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.
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);
});
@danew
Copy link
Author

danew commented Feb 23, 2024

This assumes that the alias is "~/*": ["./src/*"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment