-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
Copy pathclient.ts
285 lines (266 loc) · 10.2 KB
/
client.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import type { IncomingMessage, ServerResponse } from 'node:http'
import { join, resolve } from 'pathe'
import * as vite from 'vite'
import vuePlugin from '@vitejs/plugin-vue'
import viteJsxPlugin from '@vitejs/plugin-vue-jsx'
import type { BuildOptions, ServerOptions } from 'vite'
import { logger } from '@nuxt/kit'
import { getPort } from 'get-port-please'
import { joinURL, withoutLeadingSlash } from 'ufo'
import { defu } from 'defu'
import { env, nodeless } from 'unenv'
import { appendCorsHeaders, appendCorsPreflightHeaders, defineEventHandler } from 'h3'
import type { ViteConfig } from '@nuxt/schema'
import type { ViteBuildContext } from './vite'
import { devStyleSSRPlugin } from './plugins/dev-ssr-css'
import { runtimePathsPlugin } from './plugins/paths'
import { typeCheckPlugin } from './plugins/type-check'
import { viteNodePlugin } from './vite-node'
import { createViteLogger } from './utils/logger'
export async function buildClient (ctx: ViteBuildContext) {
const nodeCompat = ctx.nuxt.options.experimental.clientNodeCompat
? {
alias: env(nodeless).alias,
define: {
global: 'globalThis',
},
}
: { alias: {}, define: {} }
const clientConfig: ViteConfig = vite.mergeConfig(ctx.config, vite.mergeConfig({
configFile: false,
base: ctx.nuxt.options.dev
? joinURL(ctx.nuxt.options.app.baseURL.replace(/^\.\//, '/') || '/', ctx.nuxt.options.app.buildAssetsDir)
: './',
experimental: {
renderBuiltUrl: (filename, { type, hostType }) => {
if (hostType !== 'js' || type === 'asset') {
// In CSS we only use relative paths until we craft a clever runtime CSS hack
return { relative: true }
}
return { runtime: `globalThis.__publicAssetsURL(${JSON.stringify(filename)})` }
},
},
css: {
devSourcemap: !!ctx.nuxt.options.sourcemap.client,
},
define: {
'process.env.NODE_ENV': JSON.stringify(ctx.config.mode),
'process.server': false,
'process.client': true,
'process.browser': true,
'process.nitro': false,
'process.prerender': false,
'import.meta.server': false,
'import.meta.client': true,
'import.meta.browser': true,
'import.meta.nitro': false,
'import.meta.prerender': false,
'module.hot': false,
...nodeCompat.define,
},
optimizeDeps: {
entries: [ctx.entry],
include: [],
// We exclude Vue and Nuxt common dependencies from optimization
// as they already ship ESM.
//
// This will help to reduce the chance for users to encounter
// common chunk conflicts that causing browser reloads.
// We should also encourage module authors to add their deps to
// `exclude` if they ships bundled ESM.
//
// Also since `exclude` is inert, it's safe to always include
// all possible deps even if they are not used yet.
//
// @see https://github.com/antfu/nuxt-better-optimize-deps#how-it-works
exclude: [
// Vue
'vue',
'@vue/runtime-core',
'@vue/runtime-dom',
'@vue/reactivity',
'@vue/shared',
'@vue/devtools-api',
'vue-router',
'vue-demi',
// Nuxt
'nuxt',
'nuxt/app',
// Nuxt Deps
'@unhead/vue',
'consola',
'defu',
'devalue',
'h3',
'hookable',
'klona',
'ofetch',
'pathe',
'ufo',
'unctx',
'unenv',
// these will never be imported on the client
'#app-manifest',
],
},
resolve: {
alias: {
// user aliases
...nodeCompat.alias,
...ctx.config.resolve?.alias,
'nitro/runtime': join(ctx.nuxt.options.buildDir, 'nitro.client.mjs'),
// work around vite optimizer bug
'#app-manifest': 'unenv/runtime/mock/empty',
},
dedupe: [
'vue',
],
},
cacheDir: resolve(ctx.nuxt.options.rootDir, ctx.config.cacheDir ?? 'node_modules/.cache/vite', 'client'),
build: {
sourcemap: ctx.nuxt.options.sourcemap.client ? ctx.config.build?.sourcemap ?? ctx.nuxt.options.sourcemap.client : false,
manifest: 'manifest.json',
outDir: resolve(ctx.nuxt.options.buildDir, 'dist/client'),
rollupOptions: {
input: { entry: ctx.entry },
},
},
plugins: [
{
name: 'nuxt:import-conditions',
enforce: 'post',
config (_config, env) {
if (env.mode !== 'test') {
return {
resolve: {
conditions: [ctx.nuxt.options.dev ? 'development' : 'production', 'web', 'browser', 'import', 'module', 'default'],
},
}
}
},
},
devStyleSSRPlugin({
srcDir: ctx.nuxt.options.srcDir,
buildAssetsURL: joinURL(ctx.nuxt.options.app.baseURL, ctx.nuxt.options.app.buildAssetsDir),
}),
runtimePathsPlugin({
sourcemap: !!ctx.nuxt.options.sourcemap.client,
}),
viteNodePlugin(ctx),
],
appType: 'custom',
server: {
warmup: {
clientFiles: [ctx.entry],
},
middlewareMode: true,
},
} satisfies vite.InlineConfig, ctx.nuxt.options.vite.$client || {}))
clientConfig.customLogger = createViteLogger(clientConfig)
// In build mode we explicitly override any vite options that vite is relying on
// to detect whether to inject production or development code (such as HMR code)
if (!ctx.nuxt.options.dev) {
clientConfig.server!.hmr = false
}
// Inject an h3-based CORS handler in preference to vite's
const useViteCors = clientConfig.server?.cors !== undefined
if (!useViteCors) {
clientConfig.server!.cors = false
}
// We want to respect users' own rollup output options
const fileNames = withoutLeadingSlash(join(ctx.nuxt.options.app.buildAssetsDir, '[hash].js'))
clientConfig.build!.rollupOptions = defu(clientConfig.build!.rollupOptions!, {
output: {
chunkFileNames: ctx.nuxt.options.dev ? undefined : fileNames,
entryFileNames: ctx.nuxt.options.dev ? 'entry.js' : fileNames,
} satisfies NonNullable<BuildOptions['rollupOptions']>['output'],
}) as any
if (clientConfig.server && clientConfig.server.hmr !== false) {
const serverDefaults: Omit<ServerOptions, 'hmr'> & { hmr: Exclude<ServerOptions['hmr'], boolean> } = {
hmr: {
protocol: ctx.nuxt.options.devServer.https ? 'wss' : undefined,
},
}
if (typeof clientConfig.server.hmr !== 'object' || !clientConfig.server.hmr.server) {
const hmrPortDefault = 24678 // Vite's default HMR port
serverDefaults.hmr!.port = await getPort({
port: hmrPortDefault,
ports: Array.from({ length: 20 }, (_, i) => hmrPortDefault + 1 + i),
})
}
if (ctx.nuxt.options.devServer.https) {
serverDefaults.https = ctx.nuxt.options.devServer.https === true ? {} : ctx.nuxt.options.devServer.https
}
clientConfig.server = defu(clientConfig.server, serverDefaults as ViteConfig['server'])
}
// Add analyze plugin if needed
if (!ctx.nuxt.options.test && ctx.nuxt.options.build.analyze && (ctx.nuxt.options.build.analyze === true || ctx.nuxt.options.build.analyze.enabled)) {
clientConfig.plugins!.push(...await import('./plugins/analyze').then(r => r.analyzePlugin(ctx)))
}
// Add type checking client panel
if (!ctx.nuxt.options.test && ctx.nuxt.options.typescript.typeCheck === true && ctx.nuxt.options.dev) {
clientConfig.plugins!.push(typeCheckPlugin({ sourcemap: !!ctx.nuxt.options.sourcemap.client }))
}
await ctx.nuxt.callHook('vite:extendConfig', clientConfig, { isClient: true, isServer: false })
clientConfig.plugins!.unshift(
vuePlugin(clientConfig.vue),
viteJsxPlugin(clientConfig.vueJsx),
)
await ctx.nuxt.callHook('vite:configResolved', clientConfig, { isClient: true, isServer: false })
// Prioritize `optimizeDeps.exclude`. If same dep is in `include` and `exclude`, remove it from `include`
clientConfig.optimizeDeps!.include = clientConfig.optimizeDeps!.include!
.filter(dep => !clientConfig.optimizeDeps!.exclude!.includes(dep))
if (ctx.nuxt.options.dev) {
// Dev
const viteServer = await vite.createServer(clientConfig)
ctx.clientServer = viteServer
ctx.nuxt.hook('close', () => viteServer.close())
await ctx.nuxt.callHook('vite:serverCreated', viteServer, { isClient: true, isServer: false })
const transformHandler = viteServer.middlewares.stack.findIndex(m => m.handle instanceof Function && m.handle.name === 'viteTransformMiddleware')
viteServer.middlewares.stack.splice(transformHandler, 0, {
route: '',
handle: (req: IncomingMessage & { _skip_transform?: boolean }, res: ServerResponse, next: (err?: any) => void) => {
// 'Skip' the transform middleware
if (req._skip_transform) { req.url = joinURL('/__skip_vite', req.url!) }
next()
},
})
const viteMiddleware = defineEventHandler(async (event) => {
const viteRoutes: string[] = []
for (const viteRoute of viteServer.middlewares.stack) {
const m = viteRoute.route
if (m.length > 1) {
viteRoutes.push(m)
}
}
if (!event.path.startsWith(clientConfig.base!) && !viteRoutes.some(route => event.path.startsWith(route))) {
// @ts-expect-error _skip_transform is a private property
event.node.req._skip_transform = true
} else if (!useViteCors) {
if (event.method === 'OPTIONS') {
appendCorsPreflightHeaders(event, {})
return null
}
appendCorsHeaders(event, {})
}
// Workaround: vite devmiddleware modifies req.url
const _originalPath = event.node.req.url
await new Promise((resolve, reject) => {
viteServer.middlewares.handle(event.node.req, event.node.res, (err: Error) => {
event.node.req.url = _originalPath
return err ? reject(err) : resolve(null)
})
})
})
await ctx.nuxt.callHook('server:devHandler', viteMiddleware)
} else {
// Build
logger.info('Building client...')
const start = Date.now()
logger.restoreAll()
await vite.build(clientConfig)
logger.wrapAll()
await ctx.nuxt.callHook('vite:compiled')
logger.success(`Client built in ${Date.now() - start}ms`)
}
}