2023-03-10 14:55:01 +00:00
|
|
|
import { pathToFileURL } from 'node:url'
|
2021-11-04 12:33:33 +00:00
|
|
|
import { readPackageJSON, resolvePackageJSON } from 'pkg-types'
|
2022-03-17 20:10:12 +00:00
|
|
|
import type { Nuxt } from '@nuxt/schema'
|
2024-06-26 09:31:45 +00:00
|
|
|
import { resolve } from 'pathe'
|
2023-03-10 14:55:01 +00:00
|
|
|
import { importModule, tryImportModule } from '../internal/esm'
|
2021-11-21 16:14:46 +00:00
|
|
|
import type { LoadNuxtConfigOptions } from './config'
|
2021-04-02 11:47:01 +00:00
|
|
|
|
2021-04-15 19:17:44 +00:00
|
|
|
export interface LoadNuxtOptions extends LoadNuxtConfigOptions {
|
2022-03-17 20:10:12 +00:00
|
|
|
/** Load nuxt with development mode */
|
2021-04-15 19:17:44 +00:00
|
|
|
dev?: boolean
|
2022-03-17 20:10:12 +00:00
|
|
|
|
|
|
|
/** Use lazy initialization of nuxt if set to false */
|
2021-04-15 19:17:44 +00:00
|
|
|
ready?: boolean
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function loadNuxt (opts: LoadNuxtOptions): Promise<Nuxt> {
|
2022-03-17 20:10:12 +00:00
|
|
|
// Backward compatibility
|
2024-06-26 09:31:45 +00:00
|
|
|
opts.cwd = resolve(opts.cwd || (opts as any).rootDir /* backwards compat */ || '.')
|
|
|
|
opts.overrides = opts.overrides || (opts as any).config as {} /* backwards compat */ || {}
|
2022-03-17 20:10:12 +00:00
|
|
|
|
|
|
|
// Apply dev as config override
|
|
|
|
opts.overrides.dev = !!opts.dev
|
2021-04-23 20:36:43 +00:00
|
|
|
|
2024-06-26 09:31:45 +00:00
|
|
|
const nearestNuxtPkg = await Promise.all(['nuxt-nightly', 'nuxt']
|
2022-03-17 20:10:12 +00:00
|
|
|
.map(pkg => resolvePackageJSON(pkg, { url: opts.cwd }).catch(() => null)))
|
2022-08-22 10:12:02 +00:00
|
|
|
.then(r => (r.filter(Boolean) as string[]).sort((a, b) => b.length - a.length)[0])
|
2021-11-04 12:33:33 +00:00
|
|
|
if (!nearestNuxtPkg) {
|
2022-03-17 20:10:12 +00:00
|
|
|
throw new Error(`Cannot find any nuxt version from ${opts.cwd}`)
|
2021-04-23 20:36:43 +00:00
|
|
|
}
|
2021-11-04 12:33:33 +00:00
|
|
|
const pkg = await readPackageJSON(nearestNuxtPkg)
|
2023-03-10 14:55:01 +00:00
|
|
|
|
2024-06-26 09:31:45 +00:00
|
|
|
const rootDir = pathToFileURL(opts.cwd!).href
|
2023-10-02 12:42:34 +00:00
|
|
|
|
2024-07-03 22:02:05 +00:00
|
|
|
const { loadNuxt } = await importModule<typeof import('nuxt')>((pkg as any)._name || pkg.name, { paths: rootDir })
|
2024-06-26 09:31:45 +00:00
|
|
|
const nuxt = await loadNuxt(opts)
|
|
|
|
return nuxt
|
2021-04-15 19:17:44 +00:00
|
|
|
}
|
|
|
|
|
2021-10-02 16:01:17 +00:00
|
|
|
export async function buildNuxt (nuxt: Nuxt): Promise<any> {
|
2023-03-10 14:55:01 +00:00
|
|
|
const rootDir = pathToFileURL(nuxt.options.rootDir).href
|
2021-04-28 15:51:42 +00:00
|
|
|
|
2024-07-03 22:02:05 +00:00
|
|
|
const { build } = await tryImportModule<typeof import('nuxt')>('nuxt-nightly', { paths: rootDir }) || await importModule<typeof import('nuxt')>('nuxt', { paths: rootDir })
|
2021-04-15 19:17:44 +00:00
|
|
|
return build(nuxt)
|
|
|
|
}
|