Nuxt/packages/nuxt3/src/nitro.ts

68 lines
2.4 KiB
TypeScript
Raw Normal View History

import { normalize } from 'upath'
2021-03-18 14:26:41 +00:00
import { wpfs, getNitroContext, createDevServer, resolveMiddleware, build, prepare, generate } from '@nuxt/nitro'
import type { Nuxt } from '@nuxt/kit'
2021-01-22 20:57:09 +00:00
export function initNitro (nuxt: Nuxt) {
// Create contexts
const nitroOptions = (nuxt.options as any).nitro || {}
const nitroContext = getNitroContext(nuxt.options, nitroOptions)
const nitroDevContext = getNitroContext(nuxt.options, { ...nitroOptions, preset: 'dev' })
2021-01-22 20:57:09 +00:00
nuxt.server = createDevServer(nitroDevContext)
if (nuxt.vfs) {
nitroContext.vfs = nuxt.vfs
nitroDevContext.vfs = nuxt.vfs
}
2021-01-22 20:57:09 +00:00
// Connect hooks
2021-04-02 19:38:11 +00:00
// @ts-ignore
nuxt.hooks.addHooks(nitroContext.nuxtHooks)
2021-01-22 20:57:09 +00:00
nuxt.hook('close', () => nitroContext._internal.hooks.callHook('close'))
nitroContext._internal.hooks.hook('nitro:document', template => nuxt.callHook('nitro:document', template))
2021-01-22 20:57:09 +00:00
2021-04-02 19:38:11 +00:00
// @ts-ignore
nuxt.hooks.addHooks(nitroDevContext.nuxtHooks)
2021-01-22 20:57:09 +00:00
nuxt.hook('close', () => nitroDevContext._internal.hooks.callHook('close'))
nitroDevContext._internal.hooks.hook('nitro:document', template => nuxt.callHook('nitro:document', template))
2021-01-22 20:57:09 +00:00
// Add nitro client plugin (to inject $fetch helper)
nuxt.hook('app:resolve', (app) => {
app.plugins.push({ src: normalize(require.resolve('@nuxt/nitro/dist/runtime/app/nitro.client.mjs')) })
})
2021-01-22 20:57:09 +00:00
// Expose process.env.NITRO_PRESET
nuxt.options.env.NITRO_PRESET = nitroContext.preset
// Wait for all modules to be ready
nuxt.hook('modules:done', async () => {
// Extend nitro with modules
await nuxt.callHook('nitro:context', nitroContext)
await nuxt.callHook('nitro:context', nitroDevContext)
// Resolve middleware
const { middleware, legacyMiddleware } = resolveMiddleware(nuxt)
2021-01-22 20:57:09 +00:00
nuxt.server.setLegacyMiddleware(legacyMiddleware)
nitroContext.middleware.push(...middleware)
nitroDevContext.middleware.push(...middleware)
})
// nuxt build/dev
nuxt.hook('build:done', async () => {
if (nuxt.options.dev) {
await build(nitroDevContext)
} else if (!nitroContext._nuxt.isStatic) {
await prepare(nitroContext)
await generate(nitroContext)
await build(nitroContext)
}
})
// nuxt dev
2021-01-22 20:57:09 +00:00
if (nuxt.options.dev) {
nitroDevContext._internal.hooks.hook('nitro:compiled', () => { nuxt.server.watch() })
nuxt.hook('build:compile', ({ compiler }) => { compiler.outputFileSystem = wpfs })
nuxt.hook('server:devMiddleware', (m) => { nuxt.server.setDevMiddleware(m) })
}
}