fix(kit): use closest nuxt package for loadNuxt (#1686)

This commit is contained in:
pooya parsa 2021-11-04 13:33:33 +01:00 committed by GitHub
parent 2166661b17
commit 9b8d44d130
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,5 +1,6 @@
import { getContext } from 'unctx' import { getContext } from 'unctx'
import { importModule, tryImportModule, tryResolveModule, RequireModuleOptions } from './utils/cjs' import { readPackageJSON, resolvePackageJSON } from 'pkg-types'
import { importModule, tryImportModule, RequireModuleOptions } from './utils/cjs'
import type { Nuxt } from './types/nuxt' import type { Nuxt } from './types/nuxt'
import type { NuxtConfig } from './types/config' import type { NuxtConfig } from './types/config'
import type { LoadNuxtConfigOptions } from './config/load' import type { LoadNuxtConfigOptions } from './config/load'
@ -21,7 +22,6 @@ export interface LoadNuxtOptions extends LoadNuxtConfigOptions {
rootDir: string rootDir: string
dev?: boolean dev?: boolean
config?: NuxtConfig config?: NuxtConfig
version?: 2 | 3
configFile?: string configFile?: string
ready?: boolean ready?: boolean
} }
@ -29,13 +29,17 @@ export interface LoadNuxtOptions extends LoadNuxtConfigOptions {
export async function loadNuxt (opts: LoadNuxtOptions): Promise<Nuxt> { export async function loadNuxt (opts: LoadNuxtOptions): Promise<Nuxt> {
const resolveOpts: RequireModuleOptions = { paths: opts.rootDir } const resolveOpts: RequireModuleOptions = { paths: opts.rootDir }
// Detect version const nearestNuxtPkg = await Promise.all(['nuxt3', 'nuxt-edge', 'nuxt']
if (!opts.version) { .map(pkg => resolvePackageJSON(pkg, { url: opts.rootDir }).catch(() => null)))
opts.version = tryResolveModule('nuxt3', resolveOpts) ? 3 : 2 .then(r => r.filter(Boolean).sort((a, b) => b.length - a.length)[0])
if (!nearestNuxtPkg) {
throw new Error(`Cannot find any nuxt version from ${opts.rootDir}`)
} }
const pkg = await readPackageJSON(nearestNuxtPkg)
const majorVersion = parseInt((pkg.version || '').split('.')[0])
// Nuxt 3 // Nuxt 3
if (opts.version !== 2) { if (majorVersion === 3) {
const { loadNuxt } = await importModule('nuxt3', resolveOpts) const { loadNuxt } = await importModule('nuxt3', resolveOpts)
const nuxt = await loadNuxt(opts) const nuxt = await loadNuxt(opts)
return nuxt return nuxt
@ -50,6 +54,7 @@ export async function loadNuxt (opts: LoadNuxtOptions): Promise<Nuxt> {
ready: opts.ready, ready: opts.ready,
envConfig: opts.envConfig envConfig: opts.envConfig
}) })
return nuxt as Nuxt return nuxt as Nuxt
} }