forked from vitejs/vite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
278 lines (251 loc) · 7.82 KB
/
index.js
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
// @ts-check
const babel = require('@babel/core')
const jsx = require('@vue/babel-plugin-jsx')
const importMeta = require('@babel/plugin-syntax-import-meta')
const { createFilter, normalizePath } = require('@rollup/pluginutils')
const hash = require('hash-sum')
const path = require('path')
const ssrRegisterHelperId = '/__vue-jsx-ssr-register-helper'
const ssrRegisterHelperCode =
`import { useSSRContext } from "vue"\n` +
`export ${ssrRegisterHelper.toString()}`
/**
* This function is serialized with toString() and evaluated as a virtual
* module during SSR
* @param {import('vue').ComponentOptions} comp
* @param {string} filename
*/
function ssrRegisterHelper(comp, filename) {
const setup = comp.setup
comp.setup = (props, ctx) => {
// @ts-ignore
const ssrContext = useSSRContext()
;(ssrContext.modules || (ssrContext.modules = new Set())).add(filename)
if (setup) {
return setup(props, ctx)
}
}
}
/**
* @typedef { import('@rollup/pluginutils').FilterPattern} FilterPattern
* @typedef { { include?: FilterPattern, exclude?: FilterPattern, babelPlugins?: any[] } } CommonOptions
*/
/**
*
* @param {import('@vue/babel-plugin-jsx').VueJSXPluginOptions & CommonOptions} options
* @returns {import('vite').Plugin}
*/
function vueJsxPlugin(options = {}) {
let root = ''
let needHmr = false
let needSourceMap = true
return {
name: 'vite:vue-jsx',
config(config) {
return {
// only apply esbuild to ts files
// since we are handling jsx and tsx now
esbuild: {
include: /\.ts$/
},
define: {
__VUE_OPTIONS_API__: true,
__VUE_PROD_DEVTOOLS__: false,
...config.define
}
}
},
configResolved(config) {
needHmr = config.command === 'serve' && !config.isProduction
needSourceMap = config.command === 'serve' || !!config.build.sourcemap
root = config.root
},
resolveId(id) {
if (id === ssrRegisterHelperId) {
return id
}
},
load(id) {
if (id === ssrRegisterHelperId) {
return ssrRegisterHelperCode
}
},
transform(code, id, opt) {
const ssr = typeof opt === 'boolean' ? opt : (opt && opt.ssr) === true
const {
include,
exclude,
babelPlugins = [],
...babelPluginOptions
} = options
const filter = createFilter(include || /\.[jt]sx$/, exclude)
if (filter(id)) {
const plugins = [importMeta, [jsx, babelPluginOptions], ...babelPlugins]
if (id.endsWith('.tsx')) {
plugins.push([
require('@babel/plugin-transform-typescript'),
// @ts-ignore
{ isTSX: true, allowExtensions: true }
])
}
const result = babel.transformSync(code, {
babelrc: false,
ast: true,
plugins,
sourceMaps: needSourceMap,
sourceFileName: id,
configFile: false
})
if (!ssr && !needHmr) {
return {
code: result.code,
map: result.map
}
}
// check for hmr injection
/**
* @type {{ name: string }[]}
*/
const declaredComponents = []
/**
* @type {{
* local: string,
* exported: string,
* id: string,
* }[]}
*/
const hotComponents = []
let hasDefault = false
for (const node of result.ast.program.body) {
if (node.type === 'VariableDeclaration') {
const names = parseComponentDecls(node, code)
if (names.length) {
declaredComponents.push(...names)
}
}
if (node.type === 'ExportNamedDeclaration') {
if (
node.declaration &&
node.declaration.type === 'VariableDeclaration'
) {
hotComponents.push(
...parseComponentDecls(node.declaration, code).map(
({ name }) => ({
local: name,
exported: name,
id: hash(id + name)
})
)
)
} else if (node.specifiers.length) {
for (const spec of node.specifiers) {
if (
spec.type === 'ExportSpecifier' &&
spec.exported.type === 'Identifier'
) {
const matched = declaredComponents.find(
({ name }) => name === spec.local.name
)
if (matched) {
hotComponents.push({
local: spec.local.name,
exported: spec.exported.name,
id: hash(id + spec.exported.name)
})
}
}
}
}
}
if (node.type === 'ExportDefaultDeclaration') {
if (node.declaration.type === 'Identifier') {
const _name = node.declaration.name
const matched = declaredComponents.find(
({ name }) => name === _name
)
if (matched) {
hotComponents.push({
local: node.declaration.name,
exported: 'default',
id: hash(id + 'default')
})
}
} else if (isDefineComponentCall(node.declaration)) {
hasDefault = true
hotComponents.push({
local: '__default__',
exported: 'default',
id: hash(id + 'default')
})
}
}
}
if (hotComponents.length) {
if (hasDefault && (needHmr || ssr)) {
result.code =
result.code.replace(
/export default defineComponent/g,
`const __default__ = defineComponent`
) + `\nexport default __default__`
}
if (needHmr && !ssr && !/\?vue&type=script/.test(id)) {
let code = result.code
let callbackCode = ``
for (const { local, exported, id } of hotComponents) {
code +=
`\n${local}.__hmrId = "${id}"` +
`\n__VUE_HMR_RUNTIME__.createRecord("${id}", ${local})`
callbackCode += `\n__VUE_HMR_RUNTIME__.reload("${id}", __${exported})`
}
code += `\nimport.meta.hot.accept(({${hotComponents
.map((c) => `${c.exported}: __${c.exported}`)
.join(',')}}) => {${callbackCode}\n})`
result.code = code
}
if (ssr) {
const normalizedId = normalizePath(path.relative(root, id))
let ssrInjectCode =
`\nimport { ssrRegisterHelper } from "${ssrRegisterHelperId}"` +
`\nconst __moduleId = ${JSON.stringify(normalizedId)}`
for (const { local } of hotComponents) {
ssrInjectCode += `\nssrRegisterHelper(${local}, __moduleId)`
}
result.code += ssrInjectCode
}
}
return {
code: result.code,
map: result.map
}
}
}
}
}
/**
* @param {import('@babel/core').types.VariableDeclaration} node
* @param {string} source
*/
function parseComponentDecls(node, source) {
const names = []
for (const decl of node.declarations) {
if (decl.id.type === 'Identifier' && isDefineComponentCall(decl.init)) {
names.push({
name: decl.id.name
})
}
}
return names
}
/**
* @param {import('@babel/core').types.Node} node
*/
function isDefineComponentCall(node) {
return (
node &&
node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'defineComponent'
)
}
module.exports = vueJsxPlugin
vueJsxPlugin.default = vueJsxPlugin