[plugin-react] Option to run the native React Compiler in a server-consumer environment, such as Vitest specs

Open
#1,535 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
55/100
Issue type
Feature
Clarity
Clearly specified
Activity status
Active
Tech stack
react, typescript, vite
Domain
testing, tooling

Research direction

Read the vite:react-compiler transform handler in dist/index.js and trace how it decides whether to compile for the client and server environments. Add an opt-in compiler environment setting that leaves Fast Refresh's client-only check intact. Verify that the default still skips server compilation and that the option enables compilation for Vitest's ssr environment.

Written by the indexing model from the issue text.

Description

Related plugins
  • plugin-react
Description

react({ compiler: true }) runs the React Compiler only when the environment consumer is not server. In @vitejs/plugin-react 6.1.2, dist/index.js, the transform handler of vite:react-compiler has:

const isClient = this.environment?.config.consumer !== "server";
// ...
const shouldCompile = isClient && (reactCompilerOptions.compilationMode === "annotation" ? /['"]use memo['"]/.test(code) : defaultCodeFilter.test(code));

That default is right for an SSR build (#627). It also applies to Vitest. Vitest transforms a spec in the ssr environment for the node and edge-runtime test environments. A project that runs component specs in node and registers a DOM in a setup file (for example with @happy-dom/global-registrator) therefore tests un-compiled components, while its app build compiles them. The specs then do not catch compiler-specific behaviour, such as a hook whose automatic memoization breaks or a component that the compiler skips.

The Babel path lets a project opt in. reactCompilerPreset() sets applyToEnvironmentHook, and a project can override it:

const preset = reactCompilerPreset()
babel({
  presets: [{ ...preset, rolldown: { ...preset.rolldown, applyToEnvironmentHook: () => true } }],
})

The native compiler option has no equivalent. A project that wants the compiler in its specs must keep the Babel compiler in its Vitest config, or copy the oxc-transform-react call from the handler into a local plugin.

Suggested solution

An environment option on the compiler options, for example:

react({
  compiler: {
    // default: (environment) => environment.config.consumer !== 'server'
    applyToEnvironment: () => true,
  },
})

Only the compiler would use it. Fast Refresh keeps its client-only check.

Alternative
  • A boolean, such as compiler: { ssr: true }.
  • Compile in every environment when Vite runs under Vitest (process.env.VITEST). This is less explicit and changes the default for current users.
Additional context

Reproduction with [email protected], @vitejs/[email protected] and [email protected]:

// src/Counter.tsx
import { useState } from 'react'

export function Counter({ label }: { label: string }) {
  const [count, setCount] = useState(0)
  return <button onClick={() => setCount(count + 1)}>{label} {count}</button>
}
// run.mjs
import react from '@vitejs/plugin-react'
import { createServer } from 'vite'

const server = await createServer({
  configFile: false,
  plugins: [react({ compiler: true })],
  server: { middlewareMode: true, hmr: false },
})
for (const env of ['client', 'ssr']) {
  const result = await server.environments[env].transformRequest('/src/Counter.tsx')
  console.log(env, /compiler-runtime/.test(result?.code ?? ''))
}
await server.close()

Output:

client true
ssr false

Vitest 5.0.3 with test.environment: 'node' transforms the spec's imports in the ssr environment, so Counter runs without the compiler.

Validations
  • Follow our Code of Conduct
  • Read the Contributing Guidelines.
  • Read the docs.
  • Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
Dominant language
TypeScript
Stars
1.2k
Forks
287
Avg merge
1d 17h
Merged PRs (30d)
19

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from vitejs/vite-plugin-react

All issues in vitejs/vite-plugin-react

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.