-
-
Notifications
You must be signed in to change notification settings - Fork 241
Expand file tree
/
Copy pathindex.ts
More file actions
619 lines (568 loc) · 18.5 KB
/
index.ts
File metadata and controls
619 lines (568 loc) · 18.5 KB
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { readFileSync } from 'node:fs'
import type * as babelCore from '@babel/core'
import type { ParserOptions, TransformOptions } from '@babel/core'
import { createFilter } from 'vite'
import * as vite from 'vite'
import type { Plugin, ResolvedConfig } from 'vite'
import {
addRefreshWrapper,
getPreambleCode,
preambleCode,
runtimePublicPath,
silenceUseClientWarning,
virtualPreamblePlugin,
} from '@vitejs/react-common'
import {
exactRegex,
makeIdFiltersToMatchWithQuery,
} from '@rolldown/pluginutils'
const _dirname = dirname(fileURLToPath(import.meta.url))
const refreshRuntimePath = join(_dirname, 'refresh-runtime.js')
// lazy load babel since it's not used during build if plugins are not used
let babel: typeof babelCore | undefined
async function loadBabel() {
if (!babel) {
babel = await import('@babel/core')
}
return babel
}
export interface Options {
include?: string | RegExp | Array<string | RegExp>
exclude?: string | RegExp | Array<string | RegExp>
/**
* Control where the JSX factory is imported from.
* https://esbuild.github.io/api/#jsx-import-source
* @default 'react'
*/
jsxImportSource?: string
/**
* Note: Skipping React import with classic runtime is not supported from v4
* @default "automatic"
*/
jsxRuntime?: 'classic' | 'automatic'
/**
* Babel configuration applied in both dev and prod.
*/
babel?:
| BabelOptions
| ((id: string, options: { ssr?: boolean }) => BabelOptions)
/**
* React Fast Refresh runtime URL prefix.
* Useful in a module federation context to enable HMR by specifying
* the host application URL in the Vite config of a remote application.
* @example
* reactRefreshHost: 'http://localhost:3000'
*/
reactRefreshHost?: string
}
export type BabelOptions = Omit<
TransformOptions,
| 'ast'
| 'filename'
| 'root'
| 'sourceFileName'
| 'sourceMaps'
| 'inputSourceMap'
>
/**
* The object type used by the `options` passed to plugins with
* an `api.reactBabel` method.
*/
export interface ReactBabelOptions extends BabelOptions {
plugins: Extract<BabelOptions['plugins'], any[]>
presets: Extract<BabelOptions['presets'], any[]>
overrides: Extract<BabelOptions['overrides'], any[]>
parserOpts: ParserOptions & {
plugins: Extract<ParserOptions['plugins'], any[]>
}
}
type ReactBabelHook = (
babelConfig: ReactBabelOptions,
context: ReactBabelHookContext,
config: ResolvedConfig,
) => void
type ReactBabelHookContext = { ssr: boolean; id: string }
export type ViteReactPluginApi = {
/**
* Manipulate the Babel options of `@vitejs/plugin-react`
*/
reactBabel?: ReactBabelHook
}
const defaultIncludeRE = /\.[tj]sx?$/
const defaultExcludeRE = /\/node_modules\//
const tsRE = /\.tsx?$/
const compilerAnnotationRE = /['"]use memo['"]/
export default function viteReact(opts: Options = {}): Plugin[] {
const include = opts.include ?? defaultIncludeRE
const exclude = opts.exclude ?? defaultExcludeRE
const filter = createFilter(include, exclude)
const jsxImportSource = opts.jsxImportSource ?? 'react'
const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`
const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`
const isRolldownVite = 'rolldownVersion' in vite
let runningInVite = false
let isProduction = true
let projectRoot = process.cwd()
let skipFastRefresh = true
let base: string
let isFullBundle = false
let runPluginOverrides:
| ((options: ReactBabelOptions, context: ReactBabelHookContext) => void)
| undefined
let staticBabelOptions: ReactBabelOptions | undefined
// Support patterns like:
// - import * as React from 'react';
// - import React from 'react';
// - import React, {useEffect} from 'react';
const importReactRE = /\bimport\s+(?:\*\s+as\s+)?React\b/
const viteBabel: Plugin = {
name: 'vite:react-babel',
enforce: 'pre',
config(_userConfig, { command }) {
if ('rolldownVersion' in vite) {
if (opts.jsxRuntime === 'classic') {
return {
oxc: {
jsx: {
runtime: 'classic',
refresh: command === 'serve',
// disable __self and __source injection even in dev
// as this plugin injects them by babel and oxc will throw
// if development is enabled and those properties are already present
development: false,
},
jsxRefreshInclude: makeIdFiltersToMatchWithQuery(include),
jsxRefreshExclude: makeIdFiltersToMatchWithQuery(exclude),
},
}
} else {
return {
oxc: {
jsx: {
runtime: 'automatic',
importSource: opts.jsxImportSource,
refresh: command === 'serve',
},
jsxRefreshInclude: makeIdFiltersToMatchWithQuery(include),
jsxRefreshExclude: makeIdFiltersToMatchWithQuery(exclude),
},
optimizeDeps: {
rolldownOptions: { transform: { jsx: { runtime: 'automatic' } } },
},
}
}
}
if (opts.jsxRuntime === 'classic') {
return {
esbuild: {
jsx: 'transform',
},
}
} else {
return {
esbuild: {
jsx: 'automatic',
// keep undefined by default so that vite's esbuild transform can prioritize jsxImportSource from tsconfig
jsxImportSource: opts.jsxImportSource,
},
optimizeDeps: { esbuildOptions: { jsx: 'automatic' } },
}
}
},
configResolved(config) {
runningInVite = true
base = config.base
// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- use ts-ignore for ecosystem-ci
// @ts-ignore only available in newer rolldown-vite
if (config.experimental.fullBundleMode) {
isFullBundle = true
}
projectRoot = config.root
isProduction = config.isProduction
skipFastRefresh =
isProduction ||
config.command === 'build' ||
config.server.hmr === false
const hooks: ReactBabelHook[] = config.plugins
.map((plugin) => plugin.api?.reactBabel)
.filter(defined)
if (hooks.length > 0) {
runPluginOverrides = (babelOptions, context) => {
hooks.forEach((hook) => hook(babelOptions, context, config))
}
} else if (typeof opts.babel !== 'function') {
// Because hooks and the callback option can mutate the Babel options
// we only create static option in this case and re-create them
// each time otherwise
staticBabelOptions = createBabelOptions(opts.babel)
if (
(isRolldownVite || skipFastRefresh) &&
canSkipBabel(staticBabelOptions.plugins, staticBabelOptions) &&
(opts.jsxRuntime === 'classic' ? isProduction : true)
) {
delete viteBabel.transform
}
}
},
options(options) {
if (!runningInVite) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- use ts-ignore for ecosystem-ci
// @ts-ignore Rolldown has `transform.jsx`
options.transform ??= {}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- use ts-ignore for ecosystem-ci
// @ts-ignore Rolldown has `transform.jsx`
options.transform.jsx = {
runtime: opts.jsxRuntime,
importSource: opts.jsxImportSource,
}
return options
}
},
transform: {
filter: {
id: {
include: makeIdFiltersToMatchWithQuery(include),
exclude: makeIdFiltersToMatchWithQuery(exclude),
},
},
async handler(code, id, options) {
const [filepath] = id.split('?')
if (!filter(filepath)) return
const ssr = options?.ssr === true
const babelOptions = (() => {
if (staticBabelOptions) return staticBabelOptions
const newBabelOptions = createBabelOptions(
typeof opts.babel === 'function'
? opts.babel(id, { ssr })
: opts.babel,
)
runPluginOverrides?.(newBabelOptions, { id, ssr })
return newBabelOptions
})()
const plugins = [...babelOptions.plugins]
// remove react-compiler plugin on non client environment
let reactCompilerPlugin = getReactCompilerPlugin(plugins)
if (reactCompilerPlugin && ssr) {
plugins.splice(plugins.indexOf(reactCompilerPlugin), 1)
reactCompilerPlugin = undefined
}
// filter by "use memo" when react-compiler { compilationMode: "annotation" }
// https://react.dev/learn/react-compiler/incremental-adoption#annotation-mode-configuration
if (
Array.isArray(reactCompilerPlugin) &&
reactCompilerPlugin[1]?.compilationMode === 'annotation' &&
!compilerAnnotationRE.test(code)
) {
plugins.splice(plugins.indexOf(reactCompilerPlugin), 1)
reactCompilerPlugin = undefined
}
const isJSX = filepath.endsWith('x')
const useFastRefresh =
!(isRolldownVite || skipFastRefresh) &&
!ssr &&
(isJSX ||
(opts.jsxRuntime === 'classic'
? importReactRE.test(code)
: code.includes(jsxImportDevRuntime) ||
code.includes(jsxImportRuntime)))
if (useFastRefresh) {
plugins.push([
await loadPlugin('react-refresh/babel'),
{ skipEnvCheck: true },
])
}
if (opts.jsxRuntime === 'classic' && isJSX) {
if (!isProduction) {
// These development plugins are only needed for the classic runtime.
plugins.push(
await loadPlugin('@babel/plugin-transform-react-jsx-self'),
await loadPlugin('@babel/plugin-transform-react-jsx-source'),
)
}
}
// Avoid parsing if no special transformation is needed
if (canSkipBabel(plugins, babelOptions)) {
return
}
const parserPlugins = [...babelOptions.parserOpts.plugins]
if (!filepath.endsWith('.ts')) {
parserPlugins.push('jsx')
}
if (tsRE.test(filepath)) {
parserPlugins.push('typescript')
}
const babel = await loadBabel()
const result = await babel.transformAsync(code, {
...babelOptions,
root: projectRoot,
filename: id,
sourceFileName: filepath,
// Required for esbuild.jsxDev to provide correct line numbers
// This creates issues the react compiler because the re-order is too important
// People should use @babel/plugin-transform-react-jsx-development to get back good line numbers
retainLines: reactCompilerPlugin
? false
: !isProduction && isJSX && opts.jsxRuntime !== 'classic',
parserOpts: {
...babelOptions.parserOpts,
sourceType: 'module',
allowAwaitOutsideFunction: true,
plugins: parserPlugins,
},
generatorOpts: {
...babelOptions.generatorOpts,
// import attributes parsing available without plugin since 7.26
importAttributesKeyword: 'with',
decoratorsBeforeExport: true,
},
plugins,
sourceMaps: true,
})
if (result) {
if (!useFastRefresh) {
return { code: result.code!, map: result.map }
}
const code = addRefreshWrapper(
result.code!,
'@vitejs/plugin-react',
id,
opts.reactRefreshHost,
)
return { code: code ?? result.code!, map: result.map }
}
},
},
}
// for rolldown-vite
const viteRefreshWrapper: Plugin = {
name: 'vite:react:refresh-wrapper',
apply: 'serve',
async applyToEnvironment(env) {
if (env.config.consumer !== 'client' || skipFastRefresh) {
return false
}
let nativePlugin: ((options: any) => Plugin) | undefined
try {
// NOTE: `+` is to bypass lint & typecheck. vite/internal exists for newer rolldown-vite
const vite = 'vite'
nativePlugin = (await import(vite + '/internal'))
.reactRefreshWrapperPlugin
} catch {}
if (
!nativePlugin ||
['7.1.10', '7.1.11', '7.1.12'].includes(vite.version)
) {
// the native plugin in 7.1.10 and 7.1.11 and 7.1.12 does not support dev properly
return true
}
delete viteRefreshWrapper.transform
return nativePlugin({
cwd: process.cwd(),
include: makeIdFiltersToMatchWithQuery(include),
exclude: makeIdFiltersToMatchWithQuery(exclude),
jsxImportSource,
reactRefreshHost: opts.reactRefreshHost ?? '',
}) as unknown as boolean
},
// we can remove this transform hook when we drop support for rolldown-vite 7.1.12 and below
transform: {
filter: {
id: {
include: makeIdFiltersToMatchWithQuery(include),
exclude: makeIdFiltersToMatchWithQuery(exclude),
},
},
handler(code, id, options) {
const ssr = options?.ssr === true
const [filepath] = id.split('?')
const isJSX = filepath.endsWith('x')
const useFastRefresh =
!skipFastRefresh &&
!ssr &&
(isJSX ||
code.includes(jsxImportDevRuntime) ||
code.includes(jsxImportRuntime))
if (!useFastRefresh) return
const newCode = addRefreshWrapper(
code,
'@vitejs/plugin-react',
id,
opts.reactRefreshHost,
)
return newCode ? { code: newCode, map: null } : undefined
},
},
}
// for rolldown-vite
const viteConfigPost: Plugin = {
name: 'vite:react:config-post',
enforce: 'post',
config(userConfig) {
if (userConfig.server?.hmr === false) {
return {
oxc: {
jsx: {
refresh: false,
},
},
// oxc option is only available in rolldown-vite
} as any
}
},
}
// for rolldown-vite + full bundle mode
const viteReactRefreshFullBundleMode: Plugin = {
name: 'vite:react-refresh-fbm',
enforce: 'pre',
transformIndexHtml: {
handler() {
if (!skipFastRefresh && isFullBundle)
return [
{
tag: 'script',
attrs: { type: 'module' },
children: getPreambleCode(base),
},
]
},
// In unbundled mode, Vite transforms any requests.
// But in full bundled mode, Vite only transforms / bundles the scripts injected in `order: 'pre'`.
order: 'pre',
},
}
const dependencies = [
'react',
'react-dom',
jsxImportDevRuntime,
jsxImportRuntime,
]
const staticBabelPlugins =
typeof opts.babel === 'object' ? (opts.babel?.plugins ?? []) : []
const reactCompilerPlugin = getReactCompilerPlugin(staticBabelPlugins)
if (reactCompilerPlugin != null) {
const reactCompilerRuntimeModule =
getReactCompilerRuntimeModule(reactCompilerPlugin)
dependencies.push(reactCompilerRuntimeModule)
}
const viteReactRefresh: Plugin = {
name: 'vite:react-refresh',
enforce: 'pre',
config: (userConfig) => ({
build: silenceUseClientWarning(userConfig),
optimizeDeps: {
include: dependencies,
},
}),
resolveId: {
filter: { id: exactRegex(runtimePublicPath) },
handler(id) {
if (id === runtimePublicPath) {
return id
}
},
},
load: {
filter: { id: exactRegex(runtimePublicPath) },
handler(id) {
if (id === runtimePublicPath) {
return readFileSync(refreshRuntimePath, 'utf-8').replace(
/__README_URL__/g,
'https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react',
)
}
},
},
transformIndexHtml() {
if (!skipFastRefresh && !isFullBundle)
return [
{
tag: 'script',
attrs: { type: 'module' },
children: getPreambleCode(base),
},
]
},
}
return [
viteBabel,
...(isRolldownVite
? [viteRefreshWrapper, viteConfigPost, viteReactRefreshFullBundleMode]
: []),
viteReactRefresh,
virtualPreamblePlugin({
name: '@vitejs/plugin-react/preamble',
isEnabled: () => !skipFastRefresh && !isFullBundle,
}),
]
}
viteReact.preambleCode = preambleCode
// Compat for require
function viteReactForCjs(this: unknown, options: Options): Plugin[] {
return viteReact.call(this, options)
}
Object.assign(viteReactForCjs, {
default: viteReactForCjs,
})
export { viteReactForCjs as 'module.exports' }
function canSkipBabel(
plugins: ReactBabelOptions['plugins'],
babelOptions: ReactBabelOptions,
) {
return !(
plugins.length ||
babelOptions.presets.length ||
babelOptions.configFile ||
babelOptions.babelrc
)
}
const loadedPlugin = new Map<string, any>()
function loadPlugin(path: string): any {
const cached = loadedPlugin.get(path)
if (cached) return cached
const promise = import(path).then((module) => {
const value = module.default || module
loadedPlugin.set(path, value)
return value
})
loadedPlugin.set(path, promise)
return promise
}
function createBabelOptions(rawOptions?: BabelOptions) {
const babelOptions = {
babelrc: false,
configFile: false,
...rawOptions,
} as ReactBabelOptions
babelOptions.plugins ||= []
babelOptions.presets ||= []
babelOptions.overrides ||= []
babelOptions.parserOpts ||= {} as any
babelOptions.parserOpts.plugins ||= []
return babelOptions
}
function defined<T>(value: T | undefined): value is T {
return value !== undefined
}
function getReactCompilerPlugin(plugins: ReactBabelOptions['plugins']) {
return plugins.find(
(p) =>
p === 'babel-plugin-react-compiler' ||
(Array.isArray(p) && p[0] === 'babel-plugin-react-compiler'),
)
}
type ReactCompilerRuntimeModule =
| 'react/compiler-runtime' // from react namespace
| 'react-compiler-runtime' // npm package
function getReactCompilerRuntimeModule(
plugin: babelCore.PluginItem,
): ReactCompilerRuntimeModule {
let moduleName: ReactCompilerRuntimeModule = 'react/compiler-runtime'
if (Array.isArray(plugin)) {
if (plugin[1]?.target === '17' || plugin[1]?.target === '18') {
moduleName = 'react-compiler-runtime'
}
}
return moduleName
}