-
-
Notifications
You must be signed in to change notification settings - Fork 197
Expand file tree
/
Copy pathindex.ts
More file actions
537 lines (497 loc) · 14.9 KB
/
Copy pathindex.ts
File metadata and controls
537 lines (497 loc) · 14.9 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import fs from 'node:fs'
import type { ModuleNode, Plugin, ViteDevServer } from 'vite'
import { createFilter, normalizePath } from 'vite'
import type {
SFCBlock,
SFCScriptCompileOptions,
SFCStyleCompileOptions,
SFCTemplateCompileOptions,
} from 'vue/compiler-sfc'
import type * as _compiler from 'vue/compiler-sfc'
import { computed, shallowRef } from 'vue'
import {
exactRegex,
makeIdFiltersToMatchWithQuery,
} from '@rolldown/pluginutils'
import { version } from '../package.json'
import { resolveCompiler } from './compiler'
import { parseVueRequest } from './utils/query'
import {
type ExtendedSFCDescriptor,
getDescriptor,
getSrcDescriptor,
getTempSrcDescriptor,
} from './utils/descriptorCache'
import { clearScriptCache, resolveScript, typeDepToSFCMap } from './script'
import { transformMain } from './main'
import { handleHotUpdate, handleTypeDepChange } from './handleHotUpdate'
import { transformTemplateAsModule } from './template'
import { transformStyle } from './style'
import { EXPORT_HELPER_ID, helperCode } from './helper'
export { parseVueRequest } from './utils/query'
export type { VueQuery } from './utils/query'
export interface Options {
include?: string | RegExp | (string | RegExp)[]
exclude?: string | RegExp | (string | RegExp)[]
/**
* In Vite, this option follows Vite's config.
*/
isProduction?: boolean
// options to pass on to vue/compiler-sfc
script?: Partial<
Omit<
SFCScriptCompileOptions,
| 'id'
| 'isProd'
| 'inlineTemplate'
| 'templateOptions'
| 'sourceMap'
| 'genDefaultAs'
| 'customElement'
| 'defineModel'
| 'propsDestructure'
>
> & {
/**
* @deprecated defineModel is now a stable feature and always enabled if
* using Vue 3.4 or above.
*/
defineModel?: boolean
/**
* @deprecated moved to `features.propsDestructure`.
*/
propsDestructure?: boolean
}
template?: Partial<
Omit<
SFCTemplateCompileOptions,
| 'id'
| 'source'
| 'ast'
| 'filename'
| 'scoped'
| 'slotted'
| 'isProd'
| 'inMap'
| 'ssr'
| 'ssrCssVars'
| 'preprocessLang'
>
>
style?: Partial<
Omit<
SFCStyleCompileOptions,
| 'filename'
| 'id'
| 'isProd'
| 'source'
| 'scoped'
| 'cssDevSourcemap'
| 'postcssOptions'
| 'map'
| 'postcssPlugins'
| 'preprocessCustomRequire'
| 'preprocessLang'
| 'preprocessOptions'
>
>
/**
* Use custom compiler-sfc instance. Can be used to force a specific version.
*/
compiler?: typeof _compiler
/**
* Requires @vitejs/plugin-vue@^5.1.0
*/
features?: {
/**
* Enable reactive destructure for `defineProps`.
* - Available in Vue 3.4 and later.
* - **default:** `false` in Vue 3.4 (**experimental**), `true` in Vue 3.5+
*/
propsDestructure?: boolean
/**
* Transform Vue SFCs into custom elements.
* - `true`: all `*.vue` imports are converted into custom elements
* - `string | RegExp`: matched files are converted into custom elements
* - **default:** /\.ce\.vue$/
*/
customElement?: boolean | string | RegExp | (string | RegExp)[]
/**
* Force all <script setup> Vue SFC (`.vue`) files to compile in Vapor mode.
* When enabled, this acts as a plugin-level fallback for SFCs without the
* per-file `vapor` marker.
* - Available in Vue 3.6 and later.
* - **default:** `false`
*/
vapor?: boolean
/**
* Set to `false` to disable Options API support and allow related code in
* Vue core to be dropped via dead-code elimination in production builds,
* resulting in smaller bundles.
* - **default:** `true`
*/
optionsAPI?: boolean
/**
* Set to `true` to enable devtools support in production builds.
* Results in slightly larger bundles.
* - **default:** `false`
*/
prodDevtools?: boolean
/**
* Set to `true` to enable detailed information for hydration mismatch
* errors in production builds. Results in slightly larger bundles.
* - **default:** `false`
*/
prodHydrationMismatchDetails?: boolean
/**
* Customize the component ID generation strategy.
* - `'filepath'`: hash the file path (relative to the project root)
* - `'filepath-source'`: hash the file path and the source code
* - `function`: custom function that takes the file path, source code,
* whether in production mode, and the default hash function as arguments
* - **default:** `'filepath'` in development, `'filepath-source'` in production
*/
componentIdGenerator?:
| 'filepath'
| 'filepath-source'
| ((
filepath: string,
source: string,
isProduction: boolean | undefined,
getHash: (text: string) => string,
) => string)
}
/**
* @deprecated moved to `features.customElement`.
*/
customElement?: boolean | string | RegExp | (string | RegExp)[]
}
export interface ResolvedOptions extends Omit<Options, 'include' | 'exclude'> {
compiler: typeof _compiler
root: string
sourceMap: boolean
cssDevSourcemap: boolean
devServer?: ViteDevServer
devToolsEnabled?: boolean
}
export interface Api {
get options(): ResolvedOptions
set options(value: ResolvedOptions)
get include(): string | RegExp | (string | RegExp)[] | undefined
/** include cannot be updated after `options` hook is called */
set include(value: string | RegExp | (string | RegExp)[] | undefined)
get exclude(): string | RegExp | (string | RegExp)[] | undefined
/** exclude cannot be updated after `options` hook is called */
set exclude(value: string | RegExp | (string | RegExp)[] | undefined)
version: string
}
export default function vuePlugin(rawOptions: Options = {}): Plugin<Api> {
clearScriptCache()
const options = shallowRef<ResolvedOptions>({
isProduction: process.env.NODE_ENV === 'production',
compiler: null as any, // to be set in buildStart
customElement: /\.ce\.vue$/,
...rawOptions,
root: process.cwd(),
sourceMap: true,
cssDevSourcemap: false,
})
const include = shallowRef<Exclude<Options['include'], undefined>>(
rawOptions.include ?? /\.vue$/,
)
const exclude = shallowRef<Options['exclude']>(rawOptions.exclude)
let optionsHookIsCalled = false
const filter = computed(() => createFilter(include.value, exclude.value))
const customElementFilter = computed(() => {
const customElement =
options.value.features?.customElement || options.value.customElement
return typeof customElement === 'boolean'
? () => customElement
: createFilter(customElement)
})
let transformCachedModule = false
const plugin: Plugin<Api> = {
name: 'vite:vue',
api: {
get options() {
return options.value
},
set options(value) {
options.value = value
},
get include() {
return include.value
},
set include(value) {
if (optionsHookIsCalled) {
throw new Error(
'include cannot be updated after `options` hook is called',
)
}
include.value = value
},
get exclude() {
return exclude.value
},
set exclude(value) {
if (optionsHookIsCalled) {
throw new Error(
'exclude cannot be updated after `options` hook is called',
)
}
exclude.value = value
},
version,
},
handleHotUpdate(ctx) {
ctx.server.ws.send({
type: 'custom',
event: 'file-changed',
data: { file: normalizePath(ctx.file) },
})
if (options.value.compiler.invalidateTypeCache) {
options.value.compiler.invalidateTypeCache(ctx.file)
}
let typeDepModules: ModuleNode[] | undefined
const matchesFilter = filter.value(ctx.file)
if (typeDepToSFCMap.has(ctx.file)) {
typeDepModules = handleTypeDepChange(
typeDepToSFCMap.get(ctx.file)!,
ctx,
)
if (!matchesFilter) return typeDepModules
}
if (matchesFilter) {
return handleHotUpdate(
ctx,
options.value,
customElementFilter.value(ctx.file),
typeDepModules,
)
}
},
config(config) {
const parseDefine = (v: unknown) => {
try {
return typeof v === 'string' ? JSON.parse(v) : v
} catch (err) {
return v
}
}
return {
resolve: {
dedupe: config.build?.ssr ? [] : ['vue'],
},
define: {
__VUE_OPTIONS_API__:
options.value.features?.optionsAPI ??
parseDefine(config.define?.__VUE_OPTIONS_API__) ??
true,
__VUE_PROD_DEVTOOLS__:
(options.value.features?.prodDevtools ||
parseDefine(config.define?.__VUE_PROD_DEVTOOLS__)) ??
false,
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__:
(options.value.features?.prodHydrationMismatchDetails ||
parseDefine(
config.define?.__VUE_PROD_HYDRATION_MISMATCH_DETAILS__,
)) ??
false,
},
ssr: {
// @ts-ignore -- config.legacy.buildSsrCjsExternalHeuristics will be removed in Vite 5
external: config.legacy?.buildSsrCjsExternalHeuristics
? ['vue', '@vue/server-renderer']
: [],
},
}
},
configResolved(config) {
options.value = {
...options.value,
root: config.root,
sourceMap: config.command === 'build' ? !!config.build.sourcemap : true,
cssDevSourcemap: config.css?.devSourcemap ?? false,
isProduction: config.isProduction,
devToolsEnabled: !!(
options.value.features?.prodDevtools ||
config.define!.__VUE_PROD_DEVTOOLS__ ||
!config.isProduction
),
}
// #507 suppress warnings for non-recognized pseudo selectors from lightningcss
const _warn = config.logger.warn
config.logger.warn = (...args) => {
const msg = args[0]
if (
msg.match(
/\[lightningcss\] '(deep|slotted|global)' is not recognized as a valid pseudo-/,
)
) {
return
}
_warn(...args)
}
transformCachedModule =
config.command === 'build' &&
options.value.sourceMap &&
config.build.watch != null
},
options() {
type TransformObjectHook = Extract<
typeof plugin.transform,
{ filter?: unknown }
>
optionsHookIsCalled = true
;(plugin.transform as TransformObjectHook).filter = {
id: {
include: [
...makeIdFiltersToMatchWithQuery(ensureArray(include.value)),
/[?&]vue\b/,
],
exclude: exclude.value,
},
}
},
shouldTransformCachedModule({ id }) {
if (transformCachedModule && parseVueRequest(id).query.vue) {
return true
}
return false
},
configureServer(server) {
options.value.devServer = server
},
buildStart() {
const compiler = (options.value.compiler =
options.value.compiler || resolveCompiler(options.value.root))
if (compiler.invalidateTypeCache) {
options.value.devServer?.watcher.on('unlink', (file) => {
compiler.invalidateTypeCache(file)
})
}
},
resolveId: {
filter: {
id: [exactRegex(EXPORT_HELPER_ID), /[?&]vue\b/],
},
handler(id) {
// component export helper
if (id === EXPORT_HELPER_ID) {
return id
}
// serve sub-part requests (*?vue) as virtual modules
if (parseVueRequest(id).query.vue) {
return id
}
},
},
load: {
filter: {
id: [exactRegex(EXPORT_HELPER_ID), /[?&]vue\b/],
},
handler(id, opt) {
if (id === EXPORT_HELPER_ID) {
return helperCode
}
const ssr = this.environment.config.consumer === 'server'
const { filename, query } = parseVueRequest(id)
// select corresponding block for sub-part virtual modules
if (query.vue) {
if (query.src) {
return fs.readFileSync(filename, 'utf-8')
}
const descriptor = getDescriptor(filename, options.value)!
let block: SFCBlock | null | undefined
if (query.type === 'script') {
// handle <script> + <script setup> merge via compileScript()
block = resolveScript(
descriptor,
options.value,
ssr,
customElementFilter.value(filename),
)
} else if (query.type === 'template') {
block = descriptor.template!
} else if (query.type === 'style') {
block = descriptor.styles[query.index!]
} else if (query.index != null) {
block = descriptor.customBlocks[query.index]
}
if (block) {
return {
code: block.content,
map: block.map as any,
}
}
}
},
},
transform: {
// filter is set in options() hook
handler(code, id, opt) {
const ssr = this.environment.config.consumer === 'server'
const { filename, query } = parseVueRequest(id)
if (query.raw || query.url) {
return
}
if (!filter.value(filename) && !query.vue) {
return
}
if (!query.vue) {
// main request
return transformMain(
code,
filename,
options.value,
this,
ssr,
customElementFilter.value(filename),
)
} else {
// sub block request
const descriptor: ExtendedSFCDescriptor = query.src
? getSrcDescriptor(filename, query) ||
getTempSrcDescriptor(filename, query)
: getDescriptor(filename, options.value)!
if (query.src) {
this.addWatchFile(filename)
}
if (query.type === 'template') {
return transformTemplateAsModule(
code,
filename,
descriptor,
options.value,
this,
ssr,
customElementFilter.value(filename),
)
} else if (query.type === 'style') {
return transformStyle(
code,
descriptor,
Number(query.index || 0),
options.value,
this,
filename,
)
}
}
},
},
}
return plugin
}
function ensureArray<T>(value: T | T[]): T[] {
return Array.isArray(value) ? value : [value]
}
// Compat for require
function vuePluginCjs(this: unknown, options: Options): Plugin<Api> {
return vuePlugin.call(this, options)
}
Object.assign(vuePluginCjs, {
default: vuePluginCjs,
parseVueRequest,
})
export { vuePluginCjs as 'module.exports' }