From f8b3c8334b43f222a637bb2ee922f2d10815b35d Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Tue, 6 Sep 2022 10:11:35 +0200 Subject: [PATCH] feat: `resolveAlias` utility --- README.md | 2 +- src/utils.ts | 13 +++++++++++++ test/utils.spec.ts | 36 +++++++++++++++++++++++++----------- 3 files changed, 39 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index beb90be..7a53206 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/utils.ts b/src/utils.ts index b4920e1..c02de7c 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,3 +1,5 @@ +import { normalize, join } from './path' + const pathSeparators = ['/', '\\', undefined] export function normalizeAliases (_aliases: Record) { @@ -17,6 +19,17 @@ export function normalizeAliases (_aliases: Record) { return aliases } +export function resolveAlias (path: string, aliases: Record) { + 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) { diff --git a/test/utils.spec.ts b/test/utils.spec.ts index 93dd605..8446bb8 100644 --- a/test/utils.spec.ts +++ b/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', () => {