Nuxt/packages/core/src/nuxt.js

82 lines
1.9 KiB
JavaScript
Raw Normal View History

import isPlainObject from 'lodash/isPlainObject'
2018-03-31 16:22:14 +00:00
import consola from 'consola'
2018-03-16 19:52:17 +00:00
import { Hookable, defineAlias } from '@nuxt/common'
import { getNuxtConfig } from '@nuxt/config'
import { Server } from '@nuxt/server'
2018-03-16 19:52:17 +00:00
import { version } from '../package.json'
2018-03-16 16:12:06 +00:00
import ModuleContainer from './module'
import Resolver from './resolver'
2017-06-20 11:44:47 +00:00
export default class Nuxt extends Hookable {
2017-10-30 17:41:22 +00:00
constructor(options = {}) {
super()
2017-12-13 01:09:38 +00:00
// Assign options and apply defaults
this.options = getNuxtConfig(options)
2017-06-11 14:17:36 +00:00
// Create instance of core components
this.resolver = new Resolver(this)
this.moduleContainer = new ModuleContainer(this)
this.server = new Server(this)
// Deprecated hooks
this._deprecatedHooks = {
'render:context': 'render:routeContext' // #3773
}
2017-06-11 14:17:36 +00:00
// Add Legacy aliases
this.renderer = this.server
this.render = this.server.app
defineAlias(this, this.server, [ 'renderRoute', 'renderAndGetWindow', 'showReady', 'listen' ])
defineAlias(this, this.resolver, [ 'resolveAlias', 'resolvePath' ])
// Wait for Nuxt to be ready
this.initialized = false
this._ready = this.ready().catch((err) => {
2018-04-01 20:20:46 +00:00
consola.fatal(err)
2018-03-31 16:22:14 +00:00
})
2017-06-11 14:17:36 +00:00
}
2017-11-30 10:24:06 +00:00
static get version() {
return version
2017-11-30 10:24:06 +00:00
}
2017-10-30 17:41:22 +00:00
async ready() {
2017-06-15 14:59:26 +00:00
if (this._ready) {
return this._ready
}
2017-06-13 22:09:03 +00:00
2017-10-31 11:33:15 +00:00
// Add hooks
if (isPlainObject(this.options.hooks)) {
2018-08-20 14:20:45 +00:00
this.addHooks(this.options.hooks)
2017-10-31 11:33:15 +00:00
} else if (typeof this.options.hooks === 'function') {
2017-10-30 21:39:08 +00:00
this.options.hooks(this.hook)
}
2018-01-11 13:28:45 +00:00
// Await for modules
2017-10-30 17:41:22 +00:00
await this.moduleContainer.ready()
2018-01-11 13:28:45 +00:00
// Await for server to be ready
await this.server.ready()
2017-06-13 22:09:03 +00:00
2017-06-14 18:51:14 +00:00
this.initialized = true
2018-01-11 13:28:45 +00:00
// Call ready hook
2017-10-30 21:39:08 +00:00
await this.callHook('ready', this)
return this
2016-11-07 01:34:58 +00:00
}
2017-10-30 17:41:22 +00:00
async close(callback) {
2017-10-30 21:39:08 +00:00
await this.callHook('close', this)
2017-06-20 13:12:33 +00:00
/* istanbul ignore if */
2017-06-15 22:19:53 +00:00
if (typeof callback === 'function') {
2017-06-16 12:42:45 +00:00
await callback()
2017-06-15 22:19:53 +00:00
}
2016-11-07 01:34:58 +00:00
}
}