Skip to content

Commit 11ac40a

Browse files
committed
fix(plugin-react): apply babel.plugins to project files only (vitejs#5255)
1 parent d27a8b3 commit 11ac40a

2 files changed

Lines changed: 15 additions & 5 deletions

File tree

packages/plugin-react/src/index.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,15 +160,17 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
160160
},
161161
async transform(code, id, ssr) {
162162
if (/\.(mjs|[tj]sx?)$/.test(id)) {
163+
const isJSX = id.endsWith('x')
163164
const isNodeModules = id.includes('/node_modules/')
164-
const isProjectFile = id.startsWith(projectRoot + '/') && !isNodeModules
165+
const isProjectFile =
166+
!isNodeModules && (id[0] === '\0' || id.startsWith(projectRoot + '/'))
165167

166168
const plugins = isProjectFile ? [...babelOptions.plugins] : []
167169

168170
let useFastRefresh = false
169171
if (!skipFastRefresh && !ssr && !isNodeModules) {
170172
// Modules with .js or .ts extension must import React.
171-
const isReactModule = id.endsWith('x') || importReactRE.test(code)
173+
const isReactModule = isJSX || importReactRE.test(code)
172174
if (isReactModule && filter(id)) {
173175
useFastRefresh = true
174176
plugins.push([
@@ -179,7 +181,7 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
179181
}
180182

181183
let ast: t.File | null | undefined
182-
if (!isProjectFile || id.endsWith('x')) {
184+
if (!isProjectFile || isJSX) {
183185
if (useAutomaticRuntime) {
184186
// By reverse-compiling "React.createElement" calls into JSX,
185187
// React elements provided by dependencies will also use the

packages/plugin-react/src/jsx-runtime/restore-jsx.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,23 @@ type RestoredJSX = [result: t.File | null | undefined, isCommonJS: boolean]
44

55
let babelRestoreJSX: Promise<PluginItem> | undefined
66

7+
const jsxNotFound: RestoredJSX = [null, false]
8+
79
/** Restore JSX from `React.createElement` calls */
810
export async function restoreJSX(
911
babel: typeof import('@babel/core'),
1012
code: string,
1113
filename: string
1214
): Promise<RestoredJSX> {
15+
// Avoid parsing the optimized react-dom since it will never
16+
// contain compiled JSX and it's a pretty big file (800kb).
17+
if (filename.includes('/.vite/react-dom.js')) {
18+
return jsxNotFound
19+
}
20+
1321
const [reactAlias, isCommonJS] = parseReactAlias(code)
1422
if (!reactAlias) {
15-
return [null, false]
23+
return jsxNotFound
1624
}
1725

1826
const reactJsxRE = new RegExp(
@@ -28,7 +36,7 @@ export async function restoreJSX(
2836
})
2937

3038
if (!hasCompiledJsx) {
31-
return [null, false]
39+
return jsxNotFound
3240
}
3341

3442
// Support modules that use `import {Fragment} from 'react'`

0 commit comments

Comments
 (0)