Skip to content

Commit

Permalink
fix: add resolution step if alias is wildcard at root. Closes qmhc#330
Browse files Browse the repository at this point in the history
  • Loading branch information
lachieh committed Nov 16, 2024
1 parent 4d0524e commit 7340f77
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { dirname, isAbsolute, relative, resolve } from 'node:path'

import MagicString from 'magic-string'
import ts from 'typescript'
import { isRegExp, normalizePath } from './utils'
import { importResolves, isAliasGlobal, isRegExp, normalizePath } from './utils'

import type { Alias } from 'vite'

Expand Down Expand Up @@ -71,9 +71,13 @@ function transformAlias(
matchedAlias.find,
replacement + (endsWithSlash ? '/' : '')
)
const normalizedPath = normalizePath(relative(dir, resolve(dir, truthPath)))

return normalizedPath.startsWith('.') ? normalizedPath : `./${normalizedPath}`
const absolutePath = resolve(dir, truthPath)
const normalizedPath = normalizePath(relative(dir, absolutePath))
const resultPath = normalizedPath.startsWith('.') ? normalizedPath : `./${normalizedPath}`

if (!isAliasGlobal(matchedAlias)) return resultPath
if (importResolves(absolutePath)) return resultPath
}
}

Expand Down
27 changes: 27 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,33 @@ export function parseTsAliases(basePath: string, paths: ts.MapLike<string[]>) {
return result
}

const rootAsteriskImportRE = /^(?!\.{1,2}\/)([^*]+)$/
export function isAliasGlobal(alias: Alias) {
return alias.find.toString() === rootAsteriskImportRE.toString()
}

export function importResolves(path: string) {
const files = [
'.js',
'.jsx',
'.ts',
'.tsx',
'.json',
'.mjs',
'.cjs',
'.d.ts',
'.vue',
'.vue.d.ts'
]

for (const ext of files) {
if (existsSync(path + ext)) {
return true
}
}
return false
}

export function tryGetPackageInfo(name: string) {
if (process.versions.pnp) {
const targetRequire = createRequire(import.meta.url)
Expand Down
1 change: 1 addition & 0 deletions tests/__fixtures__/resolvePath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {}
1 change: 1 addition & 0 deletions tests/__fixtures__/test.resolvePath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {}
1 change: 1 addition & 0 deletions tests/__fixtures__/utils/test.data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {}

0 comments on commit 7340f77

Please sign in to comment.