-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
serverPlugin.ts
301 lines (272 loc) · 8.04 KB
/
serverPlugin.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
import { ServerPlugin, Context } from 'vite'
import {
parse,
compileTemplate,
SFCDescriptor,
SFCBlock,
} from '@vue/component-compiler-utils'
import * as fs from 'fs-extra'
import hash_sum from 'hash-sum'
import { transform } from './esbuildService'
import { normalizeComponentCode } from './componentNormalizer'
import { vueHotReloadCode } from './vueHotReload'
import path from 'path'
import { resolveImport } from 'vite/dist/node/server/serverPluginModuleRewrite'
import { InternalResolver } from 'vite/dist/node/resolver'
import { cleanUrl } from 'vite/dist/node/utils'
import {
ensureMapEntry,
importerMap,
} from 'vite/dist/node/server/serverPluginHmr'
import { srcImportMap } from 'vite/dist/node/server/serverPluginVue'
import { TemplateCompileOptions } from '@vue/component-compiler-utils/lib/compileTemplate'
import { clientPublicPath } from 'vite/dist/node/server/serverPluginClient'
import { mergeSourceMap } from 'vite/dist/node/server/serverPluginSourceMap'
import { rewriteDefault } from '@vue/compiler-sfc'
const vueTemplateCompiler = require('vue-template-compiler')
export const vueComponentNormalizer = '/vite/vueComponentNormalizer'
export const vueHotReload = '/vite/vueHotReload'
let vueCompilerOptions: TemplateCompileOptions | null = null
export function setVueCompilerOptions(opts: TemplateCompileOptions) {
vueCompilerOptions = opts
}
export const vuePlugin: ServerPlugin = ({
root,
app,
resolver,
watcher,
config,
}) => {
app.use(async (ctx, next) => {
if (ctx.path === clientPublicPath) {
await next()
ctx.type = 'js'
ctx.body = ctx.body.replace(
/__VUE_HMR_RUNTIME__\.rerender\(path, (.+)\)/g,
'__VUE_HMR_RUNTIME__.rerender(path, m)'
)
return
}
if (ctx.path === vueHotReload) {
ctx.type = 'js'
ctx.body = vueHotReloadCode
return
}
if (ctx.path === vueComponentNormalizer) {
ctx.type = 'js'
ctx.body = normalizeComponentCode
return
}
if (!ctx.path.endsWith('.vue') && !ctx.vue) {
return next()
}
const query = ctx.query
const publicPath = ctx.path
let filePath = resolver.requestToFile(publicPath)
const source = readFile(filePath)
const descriptor = JSON.parse(
JSON.stringify(
parse({
source,
compiler: vueTemplateCompiler,
filename: filePath,
sourceRoot: root,
needMap: true,
})
)
) as SFCDescriptor
if (!descriptor) {
return
}
if (!query.type) {
// rely on vite internal sfc parse....
await next()
ctx.type = 'js'
ctx.body = await parseSFC(
root,
filePath,
publicPath,
descriptor,
resolver
)
if (descriptor.script) {
ctx.map = descriptor.script.map
}
return
}
if (query.type === 'template') {
const templateBlock = descriptor.template!
if (templateBlock && templateBlock.src) {
filePath = await resolveSrcImport(root, templateBlock, ctx, resolver)
}
ctx.type = 'js'
ctx.body = compileSFCTemplate(templateBlock, filePath, publicPath)
return
}
if (query.type === 'style') {
return next()
}
})
}
function readFile(filePath: string): string {
return fs.readFileSync(filePath).toString()
}
async function parseSFC(
root: string,
filePath: string,
publicPath: string,
descriptor: SFCDescriptor,
resolver: InternalResolver
): Promise<string> {
const hasFunctional =
descriptor.template && descriptor.template.attrs.functional
const id = hash_sum(publicPath)
// template
let templateImport = `var render, staticRenderFns`
if (descriptor.template) {
templateImport = `import { render, staticRenderFns } from "${publicPath}?type=template"`
}
// script
let scriptImport = `var script = {}`
if (descriptor.script) {
const scriptBlock = descriptor.script
let code = scriptBlock.content
if (scriptBlock && scriptBlock.src) {
const srcPath = resolveImport(root, publicPath, scriptBlock.src, resolver)
code = readFile(resolver.requestToFile(srcPath))
}
if (scriptBlock.lang === 'ts') {
const res = await transform(code, publicPath, {
loader: 'ts',
})
code = res.code
if (scriptBlock.map && scriptBlock.map.sourceRoot) {
scriptBlock.map.sourceRoot = ''
}
scriptBlock.map = mergeSourceMap(
scriptBlock.map,
JSON.parse(res.map!)
) as any
}
// rewrite export default.
scriptImport = rewriteDefault(code, 'script')
}
let stylesCode = ``
let hasScoped
if (descriptor.styles.length) {
descriptor.styles
.filter((s) => !!s.content.trim())
.forEach((s, i) => {
const styleRequest = publicPath + `?type=style&index=${i}`
if (s.scoped) hasScoped = true
if (s.module) {
const styleVar = `__style${i}`
const moduleName = typeof s.module === 'string' ? s.module : '$style'
stylesCode += `\nimport ${styleVar} from ${JSON.stringify(
styleRequest + '&module'
)}`
stylesCode += `\n__cssModules[${JSON.stringify(
moduleName
)}] = ${styleVar}`
} else {
stylesCode += `\nimport ${JSON.stringify(styleRequest)}`
}
})
}
let code =
`${scriptImport}
${templateImport}
const __cssModules = {}
${stylesCode}
/* normalize component */
import normalizer from "${vueComponentNormalizer}"
var component = normalizer(
script,
render,
staticRenderFns,
${hasFunctional ? `true` : `false`},
injectStyles,
${hasScoped ? JSON.stringify(id) : `null`},
null,
null
)
`.trim() + `\n`
code += `
function injectStyles (context) {
for(let o in __cssModules){
this[o] = __cssModules[o]
}
}
`
// TODO custom block
// if (needsHotReload) {
// code += `\n` + genHotReloadCode(id, hasFunctional, templateRequest)
// }
// // Expose filename. This is used by the devtools and Vue runtime warnings.
// if (process.env.NODE_ENV === 'production') {
// // Expose the file's full path in development, so that it can be opened
// // from the devtools.
// code += `\ncomponent.options.__file = ${JSON.stringify(rawShortFilePath.replace(/\\/g, '/'))}`
// } else if (options.exposeFilename) {
// // Libraries can opt-in to expose their components' filenames in production builds.
// // For security reasons, only expose the file's basename in production.
// code += `\ncomponent.options.__file = ${JSON.stringify(filename)}`
// }
code += `
/* hot reload */
import __VUE_HMR_RUNTIME__ from "${vueHotReload}"
import vue from "vue"
if (import.meta.hot) {
__VUE_HMR_RUNTIME__.install(vue)
if(__VUE_HMR_RUNTIME__.compatible){
if (!__VUE_HMR_RUNTIME__.isRecorded('${publicPath}')) {
__VUE_HMR_RUNTIME__.createRecord('${publicPath}', component.options)
}
} else {
console.log("The hmr is not compatible.")
}
}`
code += `\nexport default component.exports`
return code
}
function compileSFCTemplate(
block: SFCBlock,
filePath: string,
publicPath: string
): string {
const { tips, errors, code } = compileTemplate({
source: block.content,
filename: filePath,
compiler: vueTemplateCompiler,
transformAssetUrls: true,
transformAssetUrlsOptions: {
base: path.posix.dirname(publicPath),
},
isProduction: process.env.NODE_ENV === 'production',
isFunctional: !!block.attrs.functional,
optimizeSSR: false,
prettify: false,
...vueCompilerOptions,
})
if (tips) {
tips.forEach(console.warn)
}
if (errors) {
errors.forEach(console.error)
}
return code + `\nexport { render, staticRenderFns }`
}
async function resolveSrcImport(
root: string,
block: SFCBlock,
ctx: Context,
resolver: InternalResolver
) {
const importer = ctx.path
const importee = cleanUrl(resolveImport(root, importer, block.src!, resolver))
const filePath = resolver.requestToFile(importee)
block.content = (await ctx.read(filePath)).toString()
ensureMapEntry(importerMap, importee).add(ctx.path)
srcImportMap.set(filePath, ctx.url)
return filePath
}