Nuxt/packages/nuxt3/src/core/nuxt.ts

72 lines
1.9 KiB
TypeScript
Raw Normal View History

import { resolve } from 'upath'
2020-07-30 23:40:16 +00:00
import Hookable from 'hookable'
import { loadNuxtConfig, LoadNuxtOptions, Nuxt, NuxtOptions, nuxtCtx, installModule, ModuleContainer } from '@nuxt/kit'
import pagesModule from '../pages/module'
import metaModule from '../meta/module'
import componentsModule from '../components/module'
import globalImportsModule from '../global-imports/module'
import { distDir, pkgDir } from '../dirs'
2021-01-22 20:57:09 +00:00
import { initNitro } from './nitro'
2020-07-02 13:02:35 +00:00
export function createNuxt (options: NuxtOptions): Nuxt {
const hooks = new Hookable() as any as Nuxt['hooks']
2021-04-15 19:17:44 +00:00
const nuxt: Nuxt = {
options,
hooks,
callHook: hooks.callHook,
2021-04-15 19:17:44 +00:00
hook: hooks.hook,
ready: () => initNuxt(nuxt),
close: () => Promise.resolve(hooks.callHook('close', nuxt)),
vfs: {}
}
2021-04-15 19:17:44 +00:00
return nuxt
2020-08-02 15:50:35 +00:00
}
async function initNuxt (nuxt: Nuxt) {
// Register user hooks
nuxt.hooks.addHooks(nuxt.options.hooks)
2020-07-02 13:02:35 +00:00
// Set nuxt instance for useNuxt
nuxtCtx.set(nuxt)
nuxt.hook('close', () => nuxtCtx.unset())
// Init nitro
await initNitro(nuxt)
2020-07-02 13:02:35 +00:00
// Init user modules
2021-04-15 19:17:44 +00:00
await nuxt.callHook('modules:before', { nuxt } as ModuleContainer)
const modulesToInstall = [
...nuxt.options.buildModules,
...nuxt.options.modules,
...nuxt.options._modules
]
2020-07-02 13:02:35 +00:00
for (const m of modulesToInstall) {
await installModule(nuxt, m)
2020-07-02 13:02:35 +00:00
}
2021-04-15 19:17:44 +00:00
await nuxt.callHook('modules:done', { nuxt } as ModuleContainer)
2020-07-02 13:02:35 +00:00
await nuxt.callHook('ready', nuxt)
}
2020-07-02 13:02:35 +00:00
2021-04-15 19:17:44 +00:00
export async function loadNuxt (opts: LoadNuxtOptions): Promise<Nuxt> {
const options = loadNuxtConfig(opts)
// Temp
options.appDir = options.alias['#app'] = resolve(distDir, 'app')
options._majorVersion = 3
options.buildModules.push(pagesModule, metaModule, componentsModule, globalImportsModule)
options.modulesDir.push(resolve(pkgDir, 'node_modules'))
const nuxt = createNuxt(options)
2021-04-15 19:17:44 +00:00
if (opts.ready !== false) {
await nuxt.ready()
}
return nuxt
}