2022-04-15 15:19:05 +00:00
|
|
|
import { createRequire } from 'node:module'
|
|
|
|
import { pathToFileURL } from 'node:url'
|
2021-09-27 12:49:36 +00:00
|
|
|
import { normalize, dirname } 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-08-26 15:47:29 +00:00
|
|
|
return [
|
2021-07-26 14:46:19 +00:00
|
|
|
// @ts-ignore
|
|
|
|
global.__NUXT_PREPATHS__,
|
2022-08-26 15:47:29 +00:00
|
|
|
...(paths ? [] : Array.isArray(paths) ? paths : [paths]),
|
2021-07-26 14:46:19 +00:00
|
|
|
process.cwd(),
|
|
|
|
// @ts-ignore
|
|
|
|
global.__NUXT_PATHS__
|
2022-08-26 15:47:29 +00:00
|
|
|
].filter(Boolean)
|
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 tryResolveModule (id: string, paths?: string | string[]) {
|
|
|
|
try {
|
|
|
|
return resolveModule(id, paths)
|
|
|
|
} catch { return null }
|
|
|
|
}
|
|
|
|
|
|
|
|
export function requireModule (id: string, paths?: string | string[]) {
|
2021-10-02 16:01:17 +00:00
|
|
|
return _require(resolveModule(id, paths))
|
|
|
|
}
|
|
|
|
|
|
|
|
export function importModule (id: string, paths?: string | string[]) {
|
|
|
|
const resolvedPath = resolveModule(id, paths)
|
|
|
|
return import(pathToFileURL(resolvedPath).href)
|
2021-04-15 19:17:44 +00:00
|
|
|
}
|
2021-07-26 14:46:19 +00:00
|
|
|
|
|
|
|
export function getNearestPackage (id: string, paths?: string | string[]) {
|
|
|
|
while (dirname(id) !== id) {
|
|
|
|
try { return requireModule(id + '/package.json', paths) } catch { }
|
|
|
|
id = dirname(id)
|
|
|
|
}
|
|
|
|
return null
|
|
|
|
}
|