2022-04-15 15:19:05 +00:00
|
|
|
import { createRequire } from 'node:module'
|
2023-04-07 16:02:47 +00:00
|
|
|
import { dirname, normalize } from 'pathe'
|
2021-07-12 10:54:24 +00:00
|
|
|
|
2021-07-26 14:46:19 +00:00
|
|
|
export function getModulePaths (paths?: string | string[]): string[] {
|
2022-09-09 10:17:44 +00:00
|
|
|
return ([] as Array<string | undefined>)
|
|
|
|
.concat(
|
|
|
|
global.__NUXT_PREPATHS__,
|
|
|
|
paths,
|
|
|
|
process.cwd(),
|
|
|
|
global.__NUXT_PATHS__
|
|
|
|
)
|
|
|
|
.filter(Boolean) as string[]
|
2021-04-15 19:17:44 +00:00
|
|
|
}
|
|
|
|
|
2021-10-02 16:01:17 +00:00
|
|
|
const _require = createRequire(process.cwd())
|
|
|
|
|
2021-07-26 14:46:19 +00:00
|
|
|
export function resolveModule (id: string, paths?: string | string[]) {
|
2021-10-02 16:01:17 +00:00
|
|
|
return normalize(_require.resolve(id, { paths: getModulePaths(paths) }))
|
2021-07-26 14:46:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function requireModule (id: string, paths?: string | string[]) {
|
2021-10-02 16:01:17 +00:00
|
|
|
return _require(resolveModule(id, paths))
|
|
|
|
}
|
|
|
|
|
2022-09-01 10:56:18 +00:00
|
|
|
export function tryRequireModule (id: string, paths?: string | string[]) {
|
|
|
|
try { return requireModule(id, paths) } catch { return null }
|
|
|
|
}
|
|
|
|
|
2021-07-26 14:46:19 +00:00
|
|
|
export function getNearestPackage (id: string, paths?: string | string[]) {
|
|
|
|
while (dirname(id) !== id) {
|
2023-04-14 12:53:21 +00:00
|
|
|
try { return requireModule(id + '/package.json', paths) } catch {}
|
2021-07-26 14:46:19 +00:00
|
|
|
id = dirname(id)
|
|
|
|
}
|
|
|
|
return null
|
|
|
|
}
|