-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
main.ts
336 lines (313 loc) · 10.2 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
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, TransformPluginContext } from 'rollup'
import { resolveScript } from './script'
import { transformTemplateInMain } from './template'
import { isOnlyTemplateChanged } from './handleHotUpdate'
import { RawSourceMap, SourceMapConsumer, SourceMapGenerator } from 'source-map'
import { createRollupError } from './utils/error'
export async function transformMain(
code: string,
filename: string,
options: ResolvedOptions,
pluginContext: TransformPluginContext
) {
const { root, devServer, isProduction, ssr } = 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)
// 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
if (hasTemplateImport) {
;({ code: templateCode, map: templateMap } = genTemplateCode(
descriptor,
options,
pluginContext
))
}
const renderReplace = hasTemplateImport
? ssr
? `_sfc_main.ssrRender = _sfc_ssrRender`
: `_sfc_main.render = _sfc_render`
: ''
// styles
const stylesCode = genStyleCode(descriptor)
// custom blocks
const customBlocksCode = genCustomBlockCode(descriptor)
const output: string[] = [
scriptCode,
templateCode,
stylesCode,
customBlocksCode,
renderReplace
]
if (hasScoped) {
output.push(
`_sfc_main.__scopeId = ${JSON.stringify(`data-v-${descriptor.id}`)}`
)
}
if (devServer) {
// expose filename during serve for devtools to pickup
output.push(`_sfc_main.__file = ${JSON.stringify(filename)}`)
}
output.push('export default _sfc_main')
// HMR
if (devServer && !isProduction) {
output.push(`_sfc_main.__hmrId = ${JSON.stringify(descriptor.id)}`)
output.push(
`__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)`,
` }`,
`})`
)
}
// 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
}
return {
code: output.join('\n'),
map: resolvedMap || {
mappings: ''
}
}
}
function genTemplateCode(
descriptor: SFCDescriptor,
options: ResolvedOptions,
pluginContext: PluginContext
) {
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
)
} else {
if (template.src) {
linkSrcToDescriptor(template.src, descriptor)
}
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 = options.ssr ? 'ssrRender' : 'render'
return {
code: `import { ${renderFnName} as _sfc_${renderFnName} } from ${request}`,
map: undefined
}
}
}
async function genScriptCode(
descriptor: SFCDescriptor,
options: ResolvedOptions
): Promise<{
code: string
map: RawSourceMap
}> {
let scriptCode = `const _sfc_main = {}`
let map
const script = resolveScript(descriptor, options)
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 = rewriteDefault(script.content, `_sfc_main`)
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
}
} else {
if (script.src) {
linkSrcToDescriptor(script.src, descriptor)
}
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
}
}
function genStyleCode(descriptor: SFCDescriptor) {
let stylesCode = ``
let hasCSSModules = false
if (descriptor.styles.length) {
descriptor.styles.forEach((style, i) => {
if (style.src) {
linkSrcToDescriptor(style.src, descriptor)
}
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 query = `?vue&type=style&index=${i}${srcQuery}`
const styleRequest = src + query + attrsQuery
if (style.module) {
if (!hasCSSModules) {
stylesCode += `\nconst cssModules = _sfc_main.__cssModules = {}`
hasCSSModules = true
}
stylesCode += genCSSModulesCode(i, styleRequest, style.module)
} else {
stylesCode += `\nimport ${JSON.stringify(styleRequest)}`
}
// TODO SSR critical CSS collection
})
}
return stylesCode
}
function genCustomBlockCode(descriptor: SFCDescriptor) {
let code = ''
descriptor.customBlocks.forEach((block, index) => {
if (block.src) {
linkSrcToDescriptor(block.src, descriptor)
}
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
}
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}`
)
}
/**
* 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.
*/
function linkSrcToDescriptor(src: string, descriptor: SFCDescriptor) {
const srcFile = path.posix.resolve(
path.posix.dirname(descriptor.filename),
src
)
setDescriptor(srcFile, 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
}