This repository has been archived by the owner on Apr 6, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
nitro.ts
224 lines (205 loc) · 7.76 KB
/
nitro.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import { existsSync, promises as fsp } from 'node:fs'
import { resolve, join } from 'pathe'
import { createNitro, createDevServer, build, prepare, copyPublicAssets, writeTypes, scanHandlers, prerender, Nitro } from 'nitropack'
import type { NitroConfig } from 'nitropack'
import type { Nuxt } from '@nuxt/schema'
import { resolvePath } from '@nuxt/kit'
import escapeRE from 'escape-string-regexp'
import defu from 'defu'
import fsExtra from 'fs-extra'
import { dynamicEventHandler } from 'h3'
import type { Plugin } from 'rollup'
import { createHeadCore } from 'unhead'
import { renderSSRHead } from '@unhead/ssr'
import { distDir } from '../dirs'
import { ImportProtectionPlugin } from './plugins/import-protection'
export async function initNitro (nuxt: Nuxt & { _nitro?: Nitro }) {
// Resolve config
const _nitroConfig = ((nuxt.options as any).nitro || {}) as NitroConfig
const nitroConfig: NitroConfig = defu(_nitroConfig, <NitroConfig>{
debug: nuxt.options.debug,
rootDir: nuxt.options.rootDir,
workspaceDir: nuxt.options.workspaceDir,
srcDir: nuxt.options.serverDir,
dev: nuxt.options.dev,
buildDir: nuxt.options.buildDir,
esbuild: {
options: {
exclude: [
new RegExp(`node_modules\\/(?!${nuxt.options._layers.map(l => l.cwd.match(/(?<=\/)node_modules\/(.+)$/)?.[1]).filter(Boolean).map(dir => escapeRE(dir!)).join('|')})`)
]
}
},
analyze: nuxt.options.build.analyze && {
template: 'treemap',
projectRoot: nuxt.options.rootDir,
filename: join(nuxt.options.rootDir, '.nuxt/stats', '{name}.html')
},
scanDirs: nuxt.options._layers.map(layer => (layer.config.serverDir || layer.config.srcDir) && resolve(layer.cwd, layer.config.serverDir || resolve(layer.config.srcDir, 'server'))).filter(Boolean),
renderer: resolve(distDir, 'core/runtime/nitro/renderer'),
errorHandler: resolve(distDir, 'core/runtime/nitro/error'),
nodeModulesDirs: nuxt.options.modulesDir,
handlers: nuxt.options.serverHandlers,
devHandlers: [],
baseURL: nuxt.options.app.baseURL,
virtual: {
'#internal/nuxt.config.mjs': () => nuxt.vfs['#build/nuxt.config']
},
routeRules: {
'/__nuxt_error': { cache: false }
},
runtimeConfig: {
...nuxt.options.runtimeConfig,
nitro: {
envPrefix: 'NUXT_',
...nuxt.options.runtimeConfig.nitro
}
},
typescript: {
generateTsConfig: false
},
publicAssets: [
{ dir: resolve(nuxt.options.buildDir, 'dist/client') },
...nuxt.options._layers
.map(layer => join(layer.config.srcDir, layer.config.dir?.public || 'public'))
.filter(dir => existsSync(dir))
.map(dir => ({ dir }))
],
prerender: {
crawlLinks: nuxt.options._generate ?? undefined,
routes: ([] as string[])
.concat(nuxt.options.generate.routes)
.concat(nuxt.options._generate ? [nuxt.options.ssr ? '/' : '/index.html', '/200.html', '/404.html'] : [])
},
sourceMap: nuxt.options.sourcemap.server,
externals: {
inline: [
...(nuxt.options.dev
? []
: [
...nuxt.options.experimental.externalVue ? [] : ['vue', '@vue/'],
'@nuxt/',
nuxt.options.buildDir
]),
'nuxt/dist',
'nuxt3/dist',
distDir
]
},
alias: {
...nuxt.options.experimental.externalVue
? {}
: {
'vue/compiler-sfc': 'vue/compiler-sfc',
'vue/server-renderer': 'vue/server-renderer',
vue: await resolvePath(`vue/dist/vue.cjs${nuxt.options.dev ? '' : '.prod'}.js`)
},
// Vue 3 mocks
'estree-walker': 'unenv/runtime/mock/proxy',
'@babel/parser': 'unenv/runtime/mock/proxy',
'@vue/compiler-core': 'unenv/runtime/mock/proxy',
'@vue/compiler-dom': 'unenv/runtime/mock/proxy',
'@vue/compiler-ssr': 'unenv/runtime/mock/proxy',
'@vue/devtools-api': 'vue-devtools-stub',
// Paths
'#paths': resolve(distDir, 'core/runtime/nitro/paths'),
// Nuxt aliases
...nuxt.options.alias
},
replace: {
'process.env.NUXT_NO_SSR': nuxt.options.ssr === false,
'process.env.NUXT_EARLY_HINTS': nuxt.options.experimental.writeEarlyHints !== false,
'process.env.NUXT_NO_SCRIPTS': !!nuxt.options.experimental.noScripts && !nuxt.options.dev,
'process.env.NUXT_INLINE_STYLES': !!nuxt.options.experimental.inlineSSRStyles,
'process.env.NUXT_PAYLOAD_EXTRACTION': !!nuxt.options.experimental.payloadExtraction,
'process.dev': nuxt.options.dev,
__VUE_PROD_DEVTOOLS__: false
},
rollupConfig: {
plugins: []
}
})
// Add head chunk for SPA renders
const head = createHeadCore()
head.push(nuxt.options.app.head)
const headChunk = await renderSSRHead(head)
nitroConfig.virtual!['#head-static'] = `export default ${JSON.stringify(headChunk)}`
// Add fallback server for `ssr: false`
if (!nuxt.options.ssr) {
nitroConfig.virtual!['#build/dist/server/server.mjs'] = 'export default () => {}'
}
if (!nuxt.options.experimental.inlineSSRStyles) {
nitroConfig.virtual!['#build/dist/server/styles.mjs'] = 'export default {}'
}
// Register nuxt protection patterns
nitroConfig.rollupConfig!.plugins!.push(
ImportProtectionPlugin.rollup({
rootDir: nuxt.options.rootDir,
patterns: [
...['#app', /^#build(\/|$)/]
.map(p => [p, 'Vue app aliases are not allowed in server routes.']) as [RegExp | string, string][]
],
exclude: [/core[\\/]runtime[\\/]nitro[\\/]renderer/]
}) as Plugin
)
// Extend nitro config with hook
await nuxt.callHook('nitro:config', nitroConfig)
// Init nitro
const nitro = await createNitro(nitroConfig)
// Expose nitro to modules and kit
nuxt._nitro = nitro
await nuxt.callHook('nitro:init', nitro)
// Connect vfs storages
nitro.vfs = nuxt.vfs = nitro.vfs || nuxt.vfs || {}
// Connect hooks
nuxt.hook('close', () => nitro.hooks.callHook('close'))
nitro.hooks.hook('prerender:routes', (routes) => {
nuxt.callHook('prerender:routes', { routes })
})
// Setup handlers
const devMiddlewareHandler = dynamicEventHandler()
nitro.options.devHandlers.unshift({ handler: devMiddlewareHandler })
nitro.options.devHandlers.push(...nuxt.options.devServerHandlers)
nitro.options.handlers.unshift({
route: '/__nuxt_error',
lazy: true,
handler: resolve(distDir, 'core/runtime/nitro/renderer')
})
// Add typed route responses
nuxt.hook('prepare:types', async (opts) => {
if (!nuxt.options.dev) {
await scanHandlers(nitro)
await writeTypes(nitro)
}
opts.references.push({ path: resolve(nuxt.options.buildDir, 'types/nitro.d.ts') })
})
// nuxt build/dev
nuxt.hook('build:done', async () => {
await nuxt.callHook('nitro:build:before', nitro)
if (nuxt.options.dev) {
await build(nitro)
} else {
await prepare(nitro)
await copyPublicAssets(nitro)
await prerender(nitro)
if (!nuxt.options._generate) {
await build(nitro)
} else {
const distDir = resolve(nuxt.options.rootDir, 'dist')
if (!existsSync(distDir)) {
await fsp.symlink(nitro.options.output.publicDir, distDir, 'junction').catch(() => { })
}
}
}
})
// nuxt dev
if (nuxt.options.dev) {
nuxt.hook('webpack:compile', ({ compiler }) => { compiler.outputFileSystem = { ...fsExtra, join } as any })
nuxt.hook('webpack:compiled', () => { nuxt.server.reload() })
nuxt.hook('vite:compiled', () => { nuxt.server.reload() })
nuxt.hook('server:devHandler', (h) => { devMiddlewareHandler.set(h) })
nuxt.server = createDevServer(nitro)
const waitUntilCompile = new Promise<void>(resolve => nitro.hooks.hook('compiled', () => resolve()))
nuxt.hook('build:done', () => waitUntilCompile)
}
}