Skip to content

Commit

Permalink
feat: resolveAlias utility
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Sep 6, 2022
1 parent a298b7a commit f8b3c83
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 12 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -46,7 +46,7 @@ Pathe exports some extra utilities that do not exist in standard Node.js [path m
In order to use them, you can import from `pathe/utils` subpath:

```js
import { filename, normalizeAliases } from 'pathe/utils'
import { filename, normalizeAliases, resolveAlias } from 'pathe/utils'
```

## License
Expand Down
13 changes: 13 additions & 0 deletions src/utils.ts
@@ -1,3 +1,5 @@
import { normalize, join } from './path'

const pathSeparators = ['/', '\\', undefined]

export function normalizeAliases (_aliases: Record<string, string>) {
Expand All @@ -17,6 +19,17 @@ export function normalizeAliases (_aliases: Record<string, string>) {
return aliases
}

export function resolveAlias (path: string, aliases: Record<string, string>) {
const _path = normalize(path)
aliases = normalizeAliases(aliases)
for (const alias in aliases) {
if (_path.startsWith(alias)) {
return join(aliases[alias], _path.slice(alias.length))
}
}
return _path
}

const FILENAME_RE = /(^|[\\/])([^\\/]+?)(?=(\.[^.]+)?$)/

export function filename (path: string) {
Expand Down
36 changes: 25 additions & 11 deletions test/utils.spec.ts
@@ -1,25 +1,39 @@
import { describe, expect, it } from 'vitest'

import { normalizeAliases, filename } from '../src/utils'
import { normalizeAliases, filename, resolveAlias } from '../src/utils'

describe('normalizeAliases', () => {
it('should work', () => {
expect(normalizeAliases({
'@foo/bar': '@foo/bar/dist/index.mjs',
'@foo/bar/utils': '@foo/bar/dist/utils.mjs',
'@': '/root',
bingpot: '@/bingpot/index.ts',
unchanged: '@bingpot/index.ts'
})).toMatchInlineSnapshot(`
describe('alias', () => {
const _aliases = {
'@foo/bar': '@foo/bar/dist/index.mjs',
'@foo/bar/utils': '@foo/bar/dist/utils.mjs',
'@': '/root',
bingpot: '@/bingpot/index.ts',
test: '@bingpot/index.ts'
}
const aliases = normalizeAliases(_aliases)

it('normalizeAliases', () => {
expect(aliases).toMatchInlineSnapshot(`
{
"@": "/root",
"@foo/bar": "@foo/bar/dist/index.mjs",
"@foo/bar/utils": "@foo/bar/dist/utils.mjs",
"bingpot": "/root/bingpot/index.ts",
"unchanged": "@bingpot/index.ts",
"test": "@bingpot/index.ts",
}
`)
})

describe('resolveAlias', () => {
for (const [from, to] of Object.entries(aliases)) {
it(from, () => {
expect(resolveAlias(from, aliases)).toBe(to)
})
}
it('unchanged', () => {
expect(resolveAlias('foo/bar.js', aliases)).toBe('foo/bar.js')
})
})
})

describe('filename', () => {
Expand Down

0 comments on commit f8b3c83

Please sign in to comment.