Published on

TIL: Vite reads the nearest tsconfig, not the one that includes it

TIL: Vite reads the nearest tsconfig, not the one that includes it
Authors
On this page

Hundreds of tests went red with ReferenceError: React is not defined. Those components don't import React at all, and the production build was fine the whole time. I wanted to know why only the tests failed.

Two things were going on.

Vite picks the nearest tsconfig

Vite and esbuild find a tsconfig.json by walking up from each file to the nearest one. They don't check whether that file's include list covers the file.

So a component under the renderer folder landed on the main-process config, which has no jsx setting. esbuild fell back to the classic transform and wrote React.createElement into files with no React import.

Why the build didn't notice

vite build hid it. The build config loaded @vitejs/plugin-react, which sets the JSX runtime itself. The test config didn't, so only the tests broke. That's the trap.

The one-line fix

Set it in the config the components really resolve to:

{
  "compilerOptions": {
    "jsx": "react-jsx"
  }
}

The whole suite went from 28 failing files to zero.

To catch it earlier, add a tiny guard test that asserts the setting is there. I checked that the guard fails if you change the value to "react", so it tracks the behavior and not just the config text.

The takeaway: if a transform behaves differently in tests than in the build, compare which config and which plugins each one loads.