vitejs/vite-plugin-react

supporting nextjs

bitttttten opened this issue · 1 comments

Description

Currently when using Next 14, it can support features like React.cache.

For example, if my test is

// cache/index.ts
import * as React from 'react'
import { fetch } from '@/api/fetch'

export const fetcher = React.cache(
  (name: string) => {
    return fetch(name)
  },
)
// cache/index.test.tsx
import { HttpResponse } from 'msw'
import { test } from 'vitest'

import { server } from '../mocks/server'
import { fetcher } from '.'

test('cache', async () => {
  server.use(
    http.post(() => {
      return HttpResponse.json({ data: { fetcher: { items: [] } } })
    }),
  )

  const name = "hello world"

  const data1 = await fetcher(name)
  const data2 = await fetcher(name)
  const data3 = await fetcher(name)

  expect(data1).toBe(data2)
  expect(data2).toBe(data3)
})

You'll get hit with

FAIL cache/index.test.ts [ cache/index.test.ts ]
TypeError: cache is not a function
❯ cache/index.ts:9:50

and console.log(React.cache) gives you undefined.

Next.JS

nextjs actually loads react from node_modules/next/dist/compliled/next-server, for example in prod it's node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js.

Is there a way to let vitest load in this react version during the tests? Then can we not support next.js from that?

Suggested solution

I don't know. Somehow alias react to node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js.

Alternative

No response

Additional context

No response

Validations

React.cache is still available on flight client as a no-op https://github.com/facebook/react/blob/6b4646cbd0fd20a7c37f5dfcb0f12193259a6289/packages/react/src/ReactCacheClient.js#L13, so it should be possible to run the tests as long as react 19 (currently rc) is installed.
Here is a simple example https://github.com/hi-ogawa/reproductions/tree/main/vitest-325-react-cache

Next.js 15 ships with React 19 available on userland, so this'll probably come soon.

Running flight server on Vitest is totally out of the scope at this point (though I have a proof of concept with Vite 6 hi-ogawa/vite-environment-examples#49). I don't think we have anything actionable for this issue, so let me close it for now.

See also testing-library side of the issue: