mirror of
https://github.com/nuxt/nuxt.git
synced 2025-03-09 03:03:18 +00:00
43 lines
1.4 KiB
TypeScript
43 lines
1.4 KiB
TypeScript
import { pathToFileURL } from 'node:url'
|
|
import { interopDefault, resolvePath } from 'mlly'
|
|
|
|
export interface ResolveModuleOptions {
|
|
paths?: string | string[]
|
|
}
|
|
|
|
/**
|
|
* Resolve a module from a given root path using an algorithm patterned on
|
|
* the upcoming `import.meta.resolve`. It returns a file URL
|
|
*
|
|
* @internal
|
|
*/
|
|
export async function tryResolveModule (id: string, url: string | string[] = import.meta.url) {
|
|
try {
|
|
return await resolvePath(id, { url })
|
|
} catch {
|
|
// intentionally empty as this is a `try-` function
|
|
}
|
|
}
|
|
|
|
export async function resolveModule (id: string, options?: ResolveModuleOptions) {
|
|
return await resolvePath(id, { url: options?.paths ?? [import.meta.url] })
|
|
}
|
|
|
|
export interface ImportModuleOptions extends ResolveModuleOptions {
|
|
/** Automatically de-default the result of requiring the module. */
|
|
interopDefault?: boolean
|
|
}
|
|
|
|
export async function importModule<T = unknown> (id: string, opts?: ImportModuleOptions) {
|
|
const resolvedPath = await resolveModule(id, opts)
|
|
return import(pathToFileURL(resolvedPath).href).then(r => opts?.interopDefault !== false ? interopDefault(r) : r) as Promise<T>
|
|
}
|
|
|
|
export function tryImportModule<T = unknown> (id: string, opts?: ImportModuleOptions) {
|
|
try {
|
|
return importModule<T>(id, opts).catch(() => undefined)
|
|
} catch {
|
|
// intentionally empty as this is a `try-` function
|
|
}
|
|
}
|