2021-03-18 14:26:41 +00:00
|
|
|
import { wpfs, getNitroContext, createDevServer, resolveMiddleware, build, prepare, generate } from '@nuxt/nitro'
|
2021-04-02 11:47:01 +00:00
|
|
|
import type { Nuxt } from '@nuxt/kit'
|
2021-01-22 20:57:09 +00:00
|
|
|
|
|
|
|
export function initNitro (nuxt: Nuxt) {
|
|
|
|
// Create contexts
|
2021-04-19 20:39:11 +00:00
|
|
|
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)
|
|
|
|
|
|
|
|
// Connect hooks
|
2021-04-02 19:38:11 +00:00
|
|
|
// @ts-ignore
|
2021-04-02 11:47:01 +00:00
|
|
|
nuxt.hooks.addHooks(nitroContext.nuxtHooks)
|
2021-01-22 20:57:09 +00:00
|
|
|
nuxt.hook('close', () => nitroContext._internal.hooks.callHook('close'))
|
|
|
|
|
2021-04-02 19:38:11 +00:00
|
|
|
// @ts-ignore
|
2021-04-02 11:47:01 +00:00
|
|
|
nuxt.hooks.addHooks(nitroDevContext.nuxtHooks)
|
2021-01-22 20:57:09 +00:00
|
|
|
nuxt.hook('close', () => nitroDevContext._internal.hooks.callHook('close'))
|
|
|
|
|
|
|
|
// Expose process.env.NITRO_PRESET
|
|
|
|
nuxt.options.env.NITRO_PRESET = nitroContext.preset
|
|
|
|
|
2021-06-03 13:12:05 +00:00
|
|
|
nitroContext._internal.hooks.hook('nitro:template', template => nuxt.callHook('nitro:template', template))
|
|
|
|
|
2021-04-19 20:39:11 +00:00
|
|
|
// 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
|
2021-04-04 17:54:12 +00:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2021-04-02 11:47:01 +00:00
|
|
|
// 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) })
|
|
|
|
}
|
|
|
|
}
|