Skip to content

Commit

Permalink
fix: improve select optimal alias
Browse files Browse the repository at this point in the history
  • Loading branch information
AliRezaBeigy committed Apr 9, 2024
1 parent 18895f3 commit bf79180
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tsimportrefiner",
"version": "1.0.0",
"version": "1.1.0",
"description": "A jscodeshift script for optimizing and sorting TypeScript imports based on path aliases defined in tsconfig.",
"main": "src/index.js",
"directories": {
Expand Down
21 changes: 13 additions & 8 deletions src/tsImportRefiner.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,19 @@ function getCompilerOptions(tsconfigPath) {
* @returns {string} The aliased path, or the original path if no alias found.
*/
function convertToAlias(tsconfigPath, filePath, importPath) {
const tsconfig = tsconfigPath
? JSON.parse(fs.readFileSync(tsconfigPath, 'utf8'))
: null;
if (!tsconfig?.compilerOptions?.paths) {
if (!tsconfigPath) {
return importPath;
}

// Use getCompilerOptions to correctly read and parse tsconfig.json
const compilerOptions = getCompilerOptions(tsconfigPath);
const mappings = tsconfig.compilerOptions.paths;
const baseUrl = tsconfig.compilerOptions.baseUrl || '.';

if (!compilerOptions.paths) {
return importPath;
}

const mappings = compilerOptions.paths;
const baseUrl = compilerOptions.baseUrl || '.';

const result = ts.resolveModuleName(
importPath,
Expand All @@ -70,9 +73,11 @@ function convertToAlias(tsconfigPath, filePath, importPath) {
? resolvedPath.substring(projectRoot.length + 1)
: resolvedPath;

for (const [alias, paths] of Object.entries(mappings)) {
const sortedAliases = Object.keys(mappings).sort((a, b) => b.length - a.length);

for (const alias of sortedAliases) {
const aliasKey = alias.replace('*', '');
const aliasPaths = paths.map(p => p.replace('*', ''));
const aliasPaths = mappings[alias].map(p => p.replace('*', ''));

for (const aliasPath of aliasPaths) {
if (relativeResolvedPath.startsWith(aliasPath)) {
Expand Down

0 comments on commit bf79180

Please sign in to comment.