Skip to content

Commit eae016b

Browse files
committed
perf(react): skip react compiler when compilationMode: 'annotation' but no "use memo"
1 parent fe15467 commit eae016b

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

packages/plugin-react/src/index.ts

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ export type ViteReactPluginApi = {
102102
const defaultIncludeRE = /\.[tj]sx?$/
103103
const defaultExcludeRE = /\/node_modules\//
104104
const tsRE = /\.tsx?$/
105+
const compilerAnnotationRE = /['"]use memo['"]/
105106

106107
export default function viteReact(opts: Options = {}): Plugin[] {
107108
const include = opts.include ?? defaultIncludeRE
@@ -246,11 +247,21 @@ export default function viteReact(opts: Options = {}): Plugin[] {
246247
const plugins = [...babelOptions.plugins]
247248

248249
// remove react-compiler plugin on non client environment
249-
if (ssr) {
250-
const reactCompilerPlugin = getReactCompilerPlugin(plugins)
251-
if (reactCompilerPlugin) {
252-
plugins.splice(plugins.indexOf(reactCompilerPlugin), 1)
253-
}
250+
let reactCompilerPlugin = getReactCompilerPlugin(plugins)
251+
if (reactCompilerPlugin && ssr) {
252+
plugins.splice(plugins.indexOf(reactCompilerPlugin), 1)
253+
reactCompilerPlugin = undefined
254+
}
255+
256+
// filter by "use memo" on annotation mode
257+
// https://react.dev/learn/react-compiler/incremental-adoption#annotation-mode-configuration
258+
if (
259+
Array.isArray(reactCompilerPlugin) &&
260+
reactCompilerPlugin[1]?.compilationMode === 'annotation' &&
261+
!compilerAnnotationRE.test(code)
262+
) {
263+
plugins.splice(plugins.indexOf(reactCompilerPlugin), 1)
264+
reactCompilerPlugin = undefined
254265
}
255266

256267
const isJSX = filepath.endsWith('x')
@@ -304,10 +315,9 @@ export default function viteReact(opts: Options = {}): Plugin[] {
304315
// Required for esbuild.jsxDev to provide correct line numbers
305316
// This creates issues the react compiler because the re-order is too important
306317
// People should use @babel/plugin-transform-react-jsx-development to get back good line numbers
307-
retainLines:
308-
getReactCompilerPlugin(plugins) != null
309-
? false
310-
: !isProduction && isJSX && opts.jsxRuntime !== 'classic',
318+
retainLines: reactCompilerPlugin
319+
? false
320+
: !isProduction && isJSX && opts.jsxRuntime !== 'classic',
311321
parserOpts: {
312322
...babelOptions.parserOpts,
313323
sourceType: 'module',

0 commit comments

Comments
 (0)