-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
main.ts
423 lines (397 loc) · 12.8 KB
/
main.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
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
import qs from 'querystring'
import path from 'path'
import { rewriteDefault, SFCBlock, SFCDescriptor } from '@vue/compiler-sfc'
import { ResolvedOptions } from '.'
import {
createDescriptor,
getPrevDescriptor,
setDescriptor
} from './utils/descriptorCache'
import { PluginContext, SourceMap, TransformPluginContext } from 'rollup'
import { normalizePath } from '@rollup/pluginutils'
import { resolveScript } from './script'
import { transformTemplateInMain } from './template'
import { isOnlyTemplateChanged, isEqualBlock } from './handleHotUpdate'
import { RawSourceMap, SourceMapConsumer, SourceMapGenerator } from 'source-map'
import { createRollupError } from './utils/error'
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export async function transformMain(
code: string,
filename: string,
options: ResolvedOptions,
pluginContext: TransformPluginContext,
ssr: boolean,
asCustomElement: boolean
) {
const { root, devServer, isProduction } = options
// prev descriptor is only set and used for hmr
const prevDescriptor = getPrevDescriptor(filename)
const { descriptor, errors } = createDescriptor(
filename,
code,
root,
isProduction
)
if (errors.length) {
errors.forEach((error) =>
pluginContext.error(createRollupError(filename, error))
)
return null
}
// feature information
const hasScoped = descriptor.styles.some((s) => s.scoped)
// script
const { code: scriptCode, map } = await genScriptCode(
descriptor,
options,
pluginContext,
ssr
)
// template
// Check if we can use compile template as inlined render function
// inside <script setup>. This can only be done for build because
// inlined template cannot be individually hot updated.
const useInlineTemplate =
!devServer &&
descriptor.scriptSetup &&
!(descriptor.template && descriptor.template.src)
const hasTemplateImport = descriptor.template && !useInlineTemplate
let templateCode = ''
let templateMap: RawSourceMap | undefined
if (hasTemplateImport) {
;({ code: templateCode, map: templateMap } = await genTemplateCode(
descriptor,
options,
pluginContext,
ssr
))
}
let renderReplace = ''
if (hasTemplateImport) {
renderReplace = ssr
? `_sfc_main.ssrRender = _sfc_ssrRender`
: `_sfc_main.render = _sfc_render`
} else {
// #2128
// User may empty the template but we didn't provide rerender function before
if (
prevDescriptor &&
!isEqualBlock(descriptor.template, prevDescriptor.template)
) {
renderReplace = ssr
? `_sfc_main.ssrRender = () => {}`
: `_sfc_main.render = () => {}`
}
}
// styles
const stylesCode = await genStyleCode(
descriptor,
pluginContext,
asCustomElement
)
// custom blocks
const customBlocksCode = await genCustomBlockCode(descriptor, pluginContext)
const output: string[] = [
scriptCode,
templateCode,
stylesCode,
customBlocksCode,
renderReplace
]
if (hasScoped) {
output.push(
`_sfc_main.__scopeId = ${JSON.stringify(`data-v-${descriptor.id}`)}`
)
}
if (devServer && !isProduction) {
// expose filename during serve for devtools to pickup
output.push(`_sfc_main.__file = ${JSON.stringify(filename)}`)
}
// HMR
if (
devServer &&
devServer.config.server.hmr !== false &&
!ssr &&
!isProduction
) {
output.push(`_sfc_main.__hmrId = ${JSON.stringify(descriptor.id)}`)
output.push(
`typeof __VUE_HMR_RUNTIME__ !== 'undefined' && ` +
`__VUE_HMR_RUNTIME__.createRecord(_sfc_main.__hmrId, _sfc_main)`
)
// check if the template is the only thing that changed
if (prevDescriptor && isOnlyTemplateChanged(prevDescriptor, descriptor)) {
output.push(`export const _rerender_only = true`)
}
output.push(
`import.meta.hot.accept(({ default: updated, _rerender_only }) => {`,
` if (_rerender_only) {`,
` __VUE_HMR_RUNTIME__.rerender(updated.__hmrId, updated.render)`,
` } else {`,
` __VUE_HMR_RUNTIME__.reload(updated.__hmrId, updated)`,
` }`,
`})`
)
}
// SSR module registration by wrapping user setup
if (ssr) {
const normalizedFilename = normalizePath(
path.relative(options.root, filename)
)
output.push(
`import { useSSRContext as __vite_useSSRContext } from 'vue'`,
`const _sfc_setup = _sfc_main.setup`,
`_sfc_main.setup = (props, ctx) => {`,
` const ssrContext = __vite_useSSRContext()`,
` ;(ssrContext.modules || (ssrContext.modules = new Set())).add(${JSON.stringify(
normalizedFilename
)})`,
` return _sfc_setup ? _sfc_setup(props, ctx) : undefined`,
`}`
)
}
// if the template is inlined into the main module (indicated by the presence
// of templateMap, we need to concatenate the two source maps.
let resolvedMap = map
if (map && templateMap) {
const generator = SourceMapGenerator.fromSourceMap(
new SourceMapConsumer(map)
)
const offset = scriptCode.match(/\r?\n/g)?.length || 1
const templateMapConsumer = new SourceMapConsumer(templateMap)
templateMapConsumer.eachMapping((m) => {
generator.addMapping({
source: m.source,
original: { line: m.originalLine, column: m.originalColumn },
generated: {
line: m.generatedLine + offset,
column: m.generatedColumn
}
})
})
resolvedMap = (generator as any).toJSON()
// if this is a template only update, we will be reusing a cached version
// of the main module compile result, which has outdated sourcesContent.
resolvedMap.sourcesContent = templateMap.sourcesContent
}
output.push(`export default _sfc_main`)
return {
code: output.join('\n'),
map: resolvedMap || {
mappings: ''
}
}
}
async function genTemplateCode(
descriptor: SFCDescriptor,
options: ResolvedOptions,
pluginContext: PluginContext,
ssr: boolean
) {
const template = descriptor.template!
// If the template is not using pre-processor AND is not using external src,
// compile and inline it directly in the main module. When served in vite this
// saves an extra request per SFC which can improve load performance.
if (!template.lang && !template.src) {
return transformTemplateInMain(
template.content,
descriptor,
options,
pluginContext,
ssr
)
} else {
if (template.src) {
await linkSrcToDescriptor(template.src, descriptor, pluginContext)
}
const src = template.src || descriptor.filename
const srcQuery = template.src ? `&src` : ``
const attrsQuery = attrsToQuery(template.attrs, 'js', true)
const query = `?vue&type=template${srcQuery}${attrsQuery}`
const request = JSON.stringify(src + query)
const renderFnName = ssr ? 'ssrRender' : 'render'
return {
code: `import { ${renderFnName} as _sfc_${renderFnName} } from ${request}`,
map: undefined
}
}
}
async function genScriptCode(
descriptor: SFCDescriptor,
options: ResolvedOptions,
pluginContext: PluginContext,
ssr: boolean
): Promise<{
code: string
map: RawSourceMap
}> {
let scriptCode = `const _sfc_main = {}`
let map: RawSourceMap | SourceMap | undefined
const script = resolveScript(descriptor, options, ssr)
if (script) {
// If the script is js/ts and has no external src, it can be directly placed
// in the main module.
if (
(!script.lang || (script.lang === 'ts' && options.devServer)) &&
!script.src
) {
scriptCode = script.content
map = script.map
if (script.lang === 'ts') {
const result = await options.devServer!.transformWithEsbuild(
scriptCode,
descriptor.filename,
{ loader: 'ts' },
map
)
scriptCode = result.code
map = result.map
}
scriptCode = rewriteDefault(scriptCode, `_sfc_main`)
} else {
if (script.src) {
await linkSrcToDescriptor(script.src, descriptor, pluginContext)
}
const src = script.src || descriptor.filename
const langFallback = (script.src && path.extname(src).slice(1)) || 'js'
const attrsQuery = attrsToQuery(script.attrs, langFallback)
const srcQuery = script.src ? `&src` : ``
const query = `?vue&type=script${srcQuery}${attrsQuery}`
const request = JSON.stringify(src + query)
scriptCode =
`import _sfc_main from ${request}\n` + `export * from ${request}` // support named exports
}
}
return {
code: scriptCode,
map: map as any
}
}
async function genStyleCode(
descriptor: SFCDescriptor,
pluginContext: PluginContext,
asCustomElement: boolean
) {
let stylesCode = ``
let hasCSSModules = false
if (descriptor.styles.length) {
for (let i = 0; i < descriptor.styles.length; i++) {
const style = descriptor.styles[i]
if (style.src) {
await linkSrcToDescriptor(style.src, descriptor, pluginContext)
}
const src = style.src || descriptor.filename
// do not include module in default query, since we use it to indicate
// that the module needs to export the modules json
const attrsQuery = attrsToQuery(style.attrs, 'css')
const srcQuery = style.src ? `&src` : ``
const directQuery = asCustomElement ? `&inline` : ``
const query = `?vue&type=style&index=${i}${srcQuery}${directQuery}`
const styleRequest = src + query + attrsQuery
if (style.module) {
if (asCustomElement) {
throw new Error(
`<style module> is not supported in custom elements mode.`
)
}
if (!hasCSSModules) {
stylesCode += `\nconst cssModules = _sfc_main.__cssModules = {}`
hasCSSModules = true
}
stylesCode += genCSSModulesCode(i, styleRequest, style.module)
} else {
if (asCustomElement) {
stylesCode += `\nimport _style_${i} from ${JSON.stringify(
styleRequest
)}`
} else {
stylesCode += `\nimport ${JSON.stringify(styleRequest)}`
}
}
// TODO SSR critical CSS collection
}
if (asCustomElement) {
stylesCode += `\n_sfc_main.styles = [${descriptor.styles
.map((_, i) => `_style_${i}`)
.join(',')}]`
}
}
return stylesCode
}
function genCSSModulesCode(
index: number,
request: string,
moduleName: string | boolean
): string {
const styleVar = `style${index}`
const exposedName = typeof moduleName === 'string' ? moduleName : '$style'
// inject `.module` before extension so vite handles it as css module
const moduleRequest = request.replace(/\.(\w+)$/, '.module.$1')
return (
`\nimport ${styleVar} from ${JSON.stringify(moduleRequest)}` +
`\ncssModules["${exposedName}"] = ${styleVar}`
)
}
async function genCustomBlockCode(
descriptor: SFCDescriptor,
pluginContext: PluginContext
) {
let code = ''
for (let index = 0; index < descriptor.customBlocks.length; index++) {
const block = descriptor.customBlocks[index]
if (block.src) {
await linkSrcToDescriptor(block.src, descriptor, pluginContext)
}
const src = block.src || descriptor.filename
const attrsQuery = attrsToQuery(block.attrs, block.type)
const srcQuery = block.src ? `&src` : ``
const query = `?vue&type=${block.type}&index=${index}${srcQuery}${attrsQuery}`
const request = JSON.stringify(src + query)
code += `import block${index} from ${request}\n`
code += `if (typeof block${index} === 'function') block${index}(_sfc_main)\n`
}
return code
}
/**
* For blocks with src imports, it is important to link the imported file
* with its owner SFC descriptor so that we can get the information about
* the owner SFC when compiling that file in the transform phase.
*/
async function linkSrcToDescriptor(
src: string,
descriptor: SFCDescriptor,
pluginContext: PluginContext
) {
const srcFile =
(await pluginContext.resolve(src, descriptor.filename))?.id || src
// #1812 if the src points to a dep file, the resolved id may contain a
// version query.
setDescriptor(srcFile.replace(/\?.*$/, ''), descriptor)
}
// these are built-in query parameters so should be ignored
// if the user happen to add them as attrs
const ignoreList = ['id', 'index', 'src', 'type', 'lang', 'module']
function attrsToQuery(
attrs: SFCBlock['attrs'],
langFallback?: string,
forceLangFallback = false
): string {
let query = ``
for (const name in attrs) {
const value = attrs[name]
if (!ignoreList.includes(name)) {
query += `&${qs.escape(name)}${
value ? `=${qs.escape(String(value))}` : ``
}`
}
}
if (langFallback || attrs.lang) {
query +=
`lang` in attrs
? forceLangFallback
? `&lang.${langFallback}`
: `&lang.${attrs.lang}`
: `&lang.${langFallback}`
}
return query
}