-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
Copy pathindex.ts
292 lines (265 loc) · 8.94 KB
/
index.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
import type { ParserOptions, TransformOptions, types as t } from '@babel/core'
import * as babel from '@babel/core'
import { createFilter } from '@rollup/pluginutils'
import resolve from 'resolve'
import type { Plugin, PluginOption } from 'vite'
import {
addRefreshWrapper,
isRefreshBoundary,
preambleCode,
runtimeCode,
runtimePublicPath
} from './fast-refresh'
import { babelImportToRequire } from './jsx-runtime/babel-import-to-require'
import { restoreJSX } from './jsx-runtime/restore-jsx'
export interface Options {
include?: string | RegExp | Array<string | RegExp>
exclude?: string | RegExp | Array<string | RegExp>
/**
* Enable `react-refresh` integration. Vite disables this in prod env or build mode.
* @default true
*/
fastRefresh?: boolean
/**
* Set this to `"automatic"` to use [vite-react-jsx](https://github.com/alloc/vite-react-jsx).
* @default "automatic"
*/
jsxRuntime?: 'classic' | 'automatic'
/**
* Control where the JSX factory is imported from.
* This option is ignored when `jsxRuntime` is not `"automatic"`.
* @default "react"
*/
jsxImportSource?: string
/**
* Babel configuration applied in both dev and prod.
*/
babel?: TransformOptions
/**
* @deprecated Use `babel.parserOpts.plugins` instead
*/
parserPlugins?: ParserOptions['plugins']
}
export default function viteReact(opts: Options = {}): PluginOption[] {
// Provide default values for Rollup compat.
let base = '/'
let filter = createFilter(opts.include, opts.exclude)
let isProduction = true
let projectRoot = process.cwd()
let skipFastRefresh = opts.fastRefresh === false
let skipReactImport = false
const useAutomaticRuntime = opts.jsxRuntime !== 'classic'
const userPlugins = opts.babel?.plugins || []
const userParserPlugins =
opts.parserPlugins || opts.babel?.parserOpts?.plugins || []
const importReactRE = /(^|\n)import\s+(\*\s+as\s+)?React\s+/
const viteBabel: Plugin = {
name: 'vite:react-babel',
enforce: 'pre',
configResolved(config) {
base = config.base
projectRoot = config.root
filter = createFilter(opts.include, opts.exclude, {
resolve: projectRoot
})
isProduction = config.isProduction
skipFastRefresh = isProduction || config.command === 'build'
const jsxInject = config.esbuild && config.esbuild.jsxInject
if (jsxInject && importReactRE.test(jsxInject)) {
skipReactImport = true
config.logger.warn(
'[@vitejs/plugin-react] This plugin imports React for you automatically,' +
' so you can stop using `esbuild.jsxInject` for that purpose.'
)
}
config.plugins.forEach(
(plugin) =>
(plugin.name === 'react-refresh' ||
(plugin !== viteReactJsx && plugin.name === 'vite:react-jsx')) &&
config.logger.warn(
`[@vitejs/plugin-react] You should stop using "${plugin.name}" ` +
`since this plugin conflicts with it.`
)
)
},
async transform(code, id, ssr) {
if (/\.[tj]sx?$/.test(id)) {
const plugins = [...userPlugins]
const parserPlugins: typeof userParserPlugins = [
...userParserPlugins,
'jsx',
'importMeta',
// This plugin is applied before esbuild transforms the code,
// so we need to enable some stage 3 syntax that is supported in
// TypeScript and some environments already.
'topLevelAwait',
'classProperties',
'classPrivateProperties',
'classPrivateMethods'
]
const isTypeScript = /\.tsx?$/.test(id)
if (isTypeScript) {
parserPlugins.push('typescript')
}
const isNodeModules = id.includes('node_modules')
let useFastRefresh = false
if (!skipFastRefresh && !ssr && !isNodeModules) {
// Modules with .js or .ts extension must import React.
const isReactModule = id.endsWith('x') || code.includes('react')
if (isReactModule && filter(id)) {
useFastRefresh = true
plugins.push([
await loadPlugin('react-refresh/babel.js'),
{ skipEnvCheck: true }
])
}
}
let ast: t.File | null | undefined
if (isNodeModules || id.endsWith('x')) {
if (useAutomaticRuntime) {
// By reverse-compiling "React.createElement" calls into JSX,
// React elements provided by dependencies will also use the
// automatic runtime!
const [restoredAst, isCommonJS] = isNodeModules
? await restoreJSX(babel, code, id)
: [null, false]
if (!isNodeModules || (ast = restoredAst)) {
plugins.push([
await loadPlugin(
'@babel/plugin-transform-react-jsx' +
(isProduction ? '' : '-development')
),
{
runtime: 'automatic',
importSource: opts.jsxImportSource
}
])
// Avoid inserting `import` statements into CJS modules.
if (isCommonJS) {
plugins.push(babelImportToRequire)
}
}
} else if (!isNodeModules) {
// These plugins are only needed for the classic runtime.
if (!isProduction) {
plugins.push(
await loadPlugin('@babel/plugin-transform-react-jsx-self'),
await loadPlugin('@babel/plugin-transform-react-jsx-source')
)
}
// Even if the automatic JSX runtime is not used, we can still
// inject the React import for .jsx and .tsx modules.
if (!skipReactImport && !importReactRE.test(code)) {
code = `import React from 'react'; ` + code
}
}
}
const isReasonReact = id.endsWith('.bs.js')
const babelOpts: TransformOptions = {
babelrc: false,
configFile: false,
...opts.babel,
ast: !isReasonReact,
root: projectRoot,
filename: id,
parserOpts: {
...opts.babel?.parserOpts,
sourceType: 'module',
allowAwaitOutsideFunction: true,
plugins: parserPlugins
},
generatorOpts: {
...opts.babel?.generatorOpts,
decoratorsBeforeExport: true
},
plugins,
sourceMaps: true,
// Vite handles sourcemap flattening
inputSourceMap: false as any
}
const result = ast
? await babel.transformFromAstAsync(ast, code, babelOpts)
: await babel.transformAsync(code, babelOpts)
if (result) {
let code = result.code!
if (useFastRefresh && /\$RefreshReg\$\(/.test(code)) {
const accept = isReasonReact || isRefreshBoundary(result.ast!)
code = addRefreshWrapper(code, id, accept)
}
return {
code,
map: result.map
}
}
}
}
}
const viteReactRefresh: Plugin = {
name: 'vite:react-refresh',
enforce: 'pre',
config: () => ({
resolve: {
dedupe: ['react', 'react-dom']
}
}),
resolveId(id) {
if (id === runtimePublicPath) {
return id
}
},
load(id) {
if (id === runtimePublicPath) {
return runtimeCode
}
},
transformIndexHtml() {
if (!skipFastRefresh)
return [
{
tag: 'script',
attrs: { type: 'module' },
children: preambleCode.replace(`__BASE__`, base)
}
]
}
}
const runtimeId = 'react/jsx-runtime'
// Adapted from https://github.com/alloc/vite-react-jsx
const viteReactJsx: Plugin = {
name: 'vite:react-jsx',
enforce: 'pre',
config() {
return {
optimizeDeps: {
include: ['react/jsx-dev-runtime']
}
}
},
resolveId(id: string) {
return id === runtimeId ? id : null
},
load(id: string) {
if (id === runtimeId) {
const runtimePath = resolve.sync(runtimeId, {
basedir: projectRoot
})
const exports = ['jsx', 'jsxs', 'Fragment']
return [
`import * as jsxRuntime from ${JSON.stringify(runtimePath)}`,
// We can't use `export * from` or else any callsite that uses
// this module will be compiled to `jsxRuntime.exports.jsx`
// instead of the more concise `jsx` alias.
...exports.map((name) => `export const ${name} = jsxRuntime.${name}`)
].join('\n')
}
}
}
return [viteBabel, viteReactRefresh, useAutomaticRuntime && viteReactJsx]
}
viteReact.preambleCode = preambleCode
function loadPlugin(path: string): Promise<any> {
return import(path).then((module) => module.default || module)
}
// overwrite for cjs require('...')() usage
module.exports = viteReact
viteReact['default'] = viteReact