Skip to content

Commit

Permalink
feat: resolve file if wildcard element is used (#396)
Browse files Browse the repository at this point in the history
* test: correct path relative to configured filePath

* test: add failing test

* fix: add resolution step if alias is wildcard at root. Closes #330
  • Loading branch information
lachieh authored Dec 17, 2024
1 parent 2bf180f commit bb4650d
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 15 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
35 changes: 35 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,41 @@ 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
'.js',
'.jsx',
'.mjs',
'.cjs',
// ts
'.ts',
'.tsx',
'.mts',
'.cts',
'.d.ts',
// json
'.json',
// vue
'.vue',
'.vue.d.ts',
// svelte
'.svelte'
]

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 {}
42 changes: 30 additions & 12 deletions tests/transform.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,22 @@ describe('transform tests', () => {

it('test: transformCode (process aliases)', () => {
const aliases: Alias[] = [
// '@/*' -> '/*'
{ find: /^@\/(?!\.{1,2}\/)([^*]+)/, replacement: resolve(__dirname, '../$1') },
// '@components/*' -> '/src/components/*'
{
find: /^@components\/(?!\.{1,2}\/)([^*]+)/,
replacement: resolve(__dirname, '../src/components/$1')
},
// '~/*' -> '/src/*'
{ find: /^~\//, replacement: resolve(__dirname, '../src/') },
// '$src/*' -> '/src/*'
{ find: '$src', replacement: resolve(__dirname, '../src') },
{ find: /^(?!\.{1,2}\/)([^*]+)/, replacement: resolve(__dirname, '../src/$1') }
// '*' -> '/tests/__fixtures__/*' (needs real path here to test if local file exists)
{
find: /^(?!\.{1,2}\/)([^*]+)$/,
replacement: resolve(__dirname, '../tests/__fixtures__/$1')
}
]
const filePath = resolve(__dirname, '../src/index.ts')

Expand Down Expand Up @@ -148,7 +156,7 @@ describe('transform tests', () => {
description: 'wildcard alias at root level with relative import and dot in name',
filePath: './src/components/Sample/index.ts',
content: 'import { Sample } from "utils/test.data";',
output: "import { Sample } from '../../utils/test.data';\n"
output: "import { Sample } from '../../../tests/__fixtures__/utils/test.data';\n"
},
{
description: 'import inside folder with named alias at subfolder',
Expand Down Expand Up @@ -198,9 +206,15 @@ describe('transform tests', () => {
output: "import { utilFunction } from '../../../utils/test';\n"
},
{
description: 'alias as everything, relative import',
content: 'import { TestBase } from "test";',
output: "import { TestBase } from './test';\n"
description: 'wildcard alias at root, relative import',
filePath: './tests/__fixtures__/index.ts',
content: 'import { TestBase } from "resolvePath";',
output: "import { TestBase } from './resolvePath';\n"
},
{
description: 'wildcard alias at root, import is likely installed dependency',
content: 'import { nothingReal } from "someDependency";',
output: "import { nothingReal } from 'someDependency';\n"
}
]

Expand All @@ -216,14 +230,14 @@ describe('transform tests', () => {
'@/*': ['src/*'],
'@components/*': ['src/components/*'],
'@src': ['src'],
'*': ['src/utils/*']
'*': ['tests/__fixtures__/*']
}

const aliases = parseTsAliases(resolve(__dirname), tsPaths)
const aliases = parseTsAliases(resolve(__dirname, '..'), tsPaths)

const options = (content: string) => ({
content,
filePath: resolve(__dirname, './src/index.ts'),
filePath: resolve(__dirname, '../src/index.ts'),
aliases,
aliasesExclude: [],
staticImport: true,
Expand All @@ -243,12 +257,12 @@ describe('transform tests', () => {
"import { TestBase } from './test';\n"
)

expect(transformCode(options('import { TestBase } from "test";')).content).toEqual(
"import { TestBase } from './utils/test';\n"
expect(transformCode(options('import { TestBase } from "resolvePath";')).content).toEqual(
"import { TestBase } from '../tests/__fixtures__/resolvePath';\n"
)

expect(transformCode(options('import { TestBase } from "test.path";')).content).toEqual(
"import { TestBase } from './utils/test.path';\n"
expect(transformCode(options('import { TestBase } from "test.resolvePath";')).content).toEqual(
"import { TestBase } from '../tests/__fixtures__/test.resolvePath';\n"
)

expect(transformCode(options('import { TestBase } from "./test.path";')).content).toEqual(
Expand All @@ -258,6 +272,10 @@ describe('transform tests', () => {
expect(transformCode(options('import { TestBase } from "../test.path";')).content).toEqual(
"import { TestBase } from '../test.path';\n"
)

expect(
transformCode(options('import { someFutureImport } from "installedDependency";')).content
).toEqual("import { someFutureImport } from 'installedDependency';\n")
})

it('test: transformCode (remove pure imports)', () => {
Expand Down

0 comments on commit bb4650d

Please sign in to comment.