-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
64 lines (53 loc) · 1.63 KB
/
index.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { dirname, normalize, sep, resolve } from 'upath2';
import type { IPackageJson } from '@ts-type/package-dts';
import { sync as pkgDir } from 'pkg-dir';
/**
* @see RequireResolve
*/
export interface IOptions
{
paths?: string[];
}
export function resolvePackageCore(moduleName: string, options?: IOptions)
{
const entryPointLocation = require.resolve(moduleName, options);
const pkgRoot = pkgDir(entryPointLocation);
return {
name: moduleName,
pkgRoot,
entryPointLocation,
}
}
export function resolvePackageRoot(moduleName: string, options?: IOptions)
{
return resolvePackageCore(moduleName, options).pkgRoot
}
export function resolvePackageJsonLocation(moduleName: string, options?: IOptions)
{
return resolve(resolvePackageCore(moduleName, options).pkgRoot, 'package.json')
}
export function createResolveLocationFn(moduleName: string, options?: IOptions)
{
const { pkgRoot } = resolvePackageCore(moduleName, options);
return (path: string, ...paths: string[]) => resolve(pkgRoot, path, ...paths)
}
export function readModulePackageJson<P extends IPackageJson>(moduleName: string, options?: IOptions): P
{
return require(resolvePackageJsonLocation(moduleName, options))
}
export function resolvePackage<P extends IPackageJson>(moduleName: string, options?: IOptions)
{
const _ = resolvePackageCore(moduleName, options);
const { pkgRoot } = _;
const pkgJsonLocation: string = resolve(pkgRoot, 'package.json');
return {
..._,
pkg: require(pkgJsonLocation) as any as P,
pkgJsonLocation,
resolveLocation(path: string, ...paths: string[])
{
return resolve(pkgRoot, path, ...paths)
},
}
}
export default resolvePackage