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
/
vite-node.ts
146 lines (132 loc) · 4.44 KB
/
vite-node.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
import { pathToFileURL } from 'node:url'
import { createApp, createError, defineEventHandler, defineLazyEventHandler } from 'h3'
import { ViteNodeServer } from 'vite-node/server'
import fse from 'fs-extra'
import { resolve } from 'pathe'
import { addDevServerHandler } from '@nuxt/kit'
import type { ModuleNode, Plugin as VitePlugin } from 'vite'
import { normalizeViteManifest } from 'vue-bundle-renderer'
import { resolve as resolveModule } from 'mlly'
import { distDir } from './dirs'
import type { ViteBuildContext } from './vite'
import { isCSS } from './utils'
import { createIsExternal } from './utils/external'
// TODO: Remove this in favor of registerViteNodeMiddleware
// after Nitropack or h3 fixed for adding middlewares after setup
export function viteNodePlugin (ctx: ViteBuildContext): VitePlugin {
// Store the invalidates for the next rendering
const invalidates = new Set<string>()
return {
name: 'nuxt:vite-node-server',
enforce: 'post',
configureServer (server) {
server.middlewares.use('/__nuxt_vite_node__', createViteNodeMiddleware(ctx, invalidates))
},
handleHotUpdate ({ file, server }) {
function markInvalidate (mod: ModuleNode) {
if (!mod.id) { return }
if (invalidates.has(mod.id)) { return }
invalidates.add(mod.id)
for (const importer of mod.importers) {
markInvalidate(importer)
}
}
const mods = server.moduleGraph.getModulesByFile(file) || []
for (const mod of mods) {
markInvalidate(mod)
}
}
}
}
export function registerViteNodeMiddleware (ctx: ViteBuildContext) {
addDevServerHandler({
route: '/__nuxt_vite_node__/',
handler: createViteNodeMiddleware(ctx)
})
}
function getManifest (ctx: ViteBuildContext) {
const css = Array.from(ctx.ssrServer!.moduleGraph.urlToModuleMap.keys())
.filter(i => isCSS(i))
const manifest = normalizeViteManifest({
'@vite/client': {
file: '@vite/client',
css,
module: true,
isEntry: true
},
[ctx.entry]: {
file: ctx.entry,
isEntry: true,
module: true,
resourceType: 'script'
}
})
return manifest
}
function createViteNodeMiddleware (ctx: ViteBuildContext, invalidates: Set<string> = new Set()) {
const app = createApp()
app.use('/manifest', defineEventHandler(() => {
const manifest = getManifest(ctx)
return manifest
}))
app.use('/invalidates', defineEventHandler(() => {
const ids = Array.from(invalidates)
invalidates.clear()
return ids
}))
app.use('/module', defineLazyEventHandler(() => {
const viteServer = ctx.ssrServer!
const node: ViteNodeServer = new ViteNodeServer(viteServer, {
deps: {
inline: [
/\/(nuxt|nuxt3)\//,
/^#/,
...ctx.nuxt.options.build.transpile as string[]
]
},
transformMode: {
ssr: [/.*/],
web: []
}
})
const isExternal = createIsExternal(viteServer, ctx.nuxt.options.rootDir)
node.shouldExternalize = async (id: string) => {
const result = await isExternal(id)
if (result?.external) {
return resolveModule(result.id, { url: ctx.nuxt.options.rootDir })
}
return false
}
return async (event) => {
const moduleId = decodeURI(event.req.url!).substring(1)
if (moduleId === '/') {
throw createError({ statusCode: 400 })
}
const module = await node.fetchModule(moduleId).catch((err) => {
throw createError({ data: err })
})
return module
}
}))
return app
}
export async function initViteNodeServer (ctx: ViteBuildContext) {
// Serialize and pass vite-node runtime options
const viteNodeServerOptions = {
baseURL: `${ctx.nuxt.options.server.url}__nuxt_vite_node__`,
root: ctx.nuxt.options.srcDir,
entryPath: ctx.entry,
base: ctx.ssrServer!.config.base || '/_nuxt/'
}
process.env.NUXT_VITE_NODE_OPTIONS = JSON.stringify(viteNodeServerOptions)
const serverResolvedPath = resolve(distDir, 'runtime/vite-node.mjs')
const manifestResolvedPath = resolve(distDir, 'runtime/client.manifest.mjs')
await fse.writeFile(
resolve(ctx.nuxt.options.buildDir, 'dist/server/server.mjs'),
`export { default } from ${JSON.stringify(pathToFileURL(serverResolvedPath).href)}`
)
await fse.writeFile(
resolve(ctx.nuxt.options.buildDir, 'dist/server/client.manifest.mjs'),
`export { default } from ${JSON.stringify(pathToFileURL(manifestResolvedPath).href)}`
)
}