Nuxt/packages/nuxt3/src/nuxt.ts

108 lines
2.2 KiB
TypeScript
Raw Normal View History

import type { IncomingHttpHeaders } from 'http'
2020-07-02 13:02:35 +00:00
import { dirname } from 'path'
2020-07-02 13:02:35 +00:00
import isPlainObject from 'lodash/isPlainObject'
import consola from 'consola'
2020-07-30 23:40:16 +00:00
import Hookable from 'hookable'
import { loadNuxtConfig } from '@nuxt/kit'
import { version } from '../package.json'
2020-07-02 13:02:35 +00:00
import ModuleContainer from './module'
import Resolver from './resolver'
2021-01-22 20:57:09 +00:00
import { initNitro } from './nitro'
2020-07-02 13:02:35 +00:00
2020-08-02 15:50:35 +00:00
declare global {
namespace NodeJS {
interface Global {
__NUXT_DEV__: boolean
}
}
2020-08-02 15:50:35 +00:00
}
export class Nuxt extends Hookable {
2020-07-30 23:40:16 +00:00
_ready?: Promise<this>
_initCalled?: boolean
error?: Error & { statusCode?: number, headers?: IncomingHttpHeaders }
options: any
2020-07-30 23:40:16 +00:00
resolver: Resolver
moduleContainer: ModuleContainer
2021-01-18 11:49:50 +00:00
server?: any
renderer?: any
render?: any['app']
2020-07-30 23:40:16 +00:00
showReady?: () => void
constructor (options) {
2020-07-02 13:02:35 +00:00
super(consola)
this.options = options
2020-07-02 13:02:35 +00:00
// Create instance of core components
this.resolver = new Resolver(this)
this.moduleContainer = new ModuleContainer(this)
// Call ready
if (this.options._ready !== false) {
this.ready().catch((err) => {
consola.fatal(err)
})
}
}
2020-08-04 10:26:22 +00:00
static get version () {
2020-07-02 13:02:35 +00:00
return `v${version}` + (global.__NUXT_DEV__ ? '-development' : '')
}
2020-08-04 10:26:22 +00:00
ready () {
2020-07-02 13:02:35 +00:00
if (!this._ready) {
this._ready = this._init()
}
return this._ready
}
2020-08-04 10:26:22 +00:00
async _init () {
2020-07-02 13:02:35 +00:00
if (this._initCalled) {
return this
}
this._initCalled = true
// Add hooks
2020-08-02 15:50:35 +00:00
if (this.options.hooks instanceof Function) {
2020-07-02 13:02:35 +00:00
this.options.hooks(this.hook)
2020-08-02 15:50:35 +00:00
} else if (isPlainObject(this.options.hooks)) {
this.addHooks(this.options.hooks)
2020-07-02 13:02:35 +00:00
}
2021-01-22 20:57:09 +00:00
// Await for server
await initNitro(this)
2020-07-02 13:02:35 +00:00
// Await for modules
await this.moduleContainer.ready()
2020-07-02 13:02:35 +00:00
// Call ready hook
await this.callHook('ready', this)
return this
}
2020-08-04 10:26:22 +00:00
async close (callback?: () => any | Promise<any>) {
2020-07-02 13:02:35 +00:00
await this.callHook('close', this)
if (typeof callback === 'function') {
await callback()
}
}
}
export async function loadNuxt (opts: LoadNuxtOptions) {
const options = await loadNuxtConfig(opts)
// Temp
options.appDir = dirname(require.resolve('@nuxt/app'))
options._majorVersion = 3
const nuxt = new Nuxt(options)
await nuxt.ready()
return nuxt
}