-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
relativeId.ts
40 lines (35 loc) · 1.28 KB
/
relativeId.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { relative } from '../../browser/src/path';
import { basename, dirname, extname, isAbsolute, normalize, resolve } from './path';
export function getAliasName(id: string): string {
const base = basename(id);
return base.slice(0, Math.max(0, base.length - extname(id).length));
}
export default function relativeId(id: string): string {
if (!isAbsolute(id)) return id;
return relative(resolve(), id);
}
export function isPathFragment(name: string): boolean {
// starting with "/", "./", "../", "C:/"
return (
name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name)
);
}
const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
export function getImportPath(
importerId: string,
targetPath: string,
stripJsExtension: boolean,
ensureFileName: boolean
): string {
let relativePath = normalize(relative(dirname(importerId), targetPath));
if (stripJsExtension && relativePath.endsWith('.js')) {
relativePath = relativePath.slice(0, -3);
}
if (ensureFileName) {
if (relativePath === '') return '../' + basename(targetPath);
if (UPPER_DIR_REGEX.test(relativePath)) {
return [...relativePath.split('/'), '..', basename(targetPath)].join('/');
}
}
return relativePath ? (relativePath.startsWith('..') ? relativePath : './' + relativePath) : '.';
}