Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

test: add ssr-react-streaming #471

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
hi-ogawa wants to merge 6 commits into vitejs:main
base: main
Choose a base branch
Loading
from hi-ogawa:fix-hydrate-while-streaming
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { expect, test } from 'vitest'
import { editFile, isBuild, page, viteTestUrl as url } from '~utils'

test('interactive before suspense is resolved', async () => {
await page.goto(url, { waitUntil: 'commit' }) // don't wait for full html
await expect
.poll(() => page.getByTestId('hydrated').textContent())
.toContain('[hydrated: 1]')
await expect
.poll(() => page.getByTestId('suspense').textContent())
.toContain('suspense-fallback')
await expect
.poll(() => page.getByTestId('suspense').textContent(), { timeout: 2000 })
.toContain('suspense-resolved')
})

test.skipIf(isBuild)('hmr', async () => {
await page.goto(url)
await expect
.poll(() => page.getByTestId('hydrated').textContent())
.toContain('[hydrated: 1]')
await page.getByTestId('counter').click()
await expect
.poll(() => page.getByTestId('counter').textContent())
.toContain('Counter: 1')
editFile('src/root.tsx', (code) => code.replace('Counter:', 'Counter-edit:'))
await expect
.poll(() => page.getByTestId('counter').textContent())
.toContain('Counter-edit: 1')
})
19 changes: 19 additions & 0 deletions playground/ssr-react-streaming/package.json
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@vitejs/test-ssr-react",
"private": true,
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build --app",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"@vitejs/plugin-react": "workspace:*"
}
}
8 changes: 8 additions & 0 deletions playground/ssr-react-streaming/src/entry-client.tsx
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import ReactDOMClient from 'react-dom/client'
import { Root } from './root'

function main() {
ReactDOMClient.hydrateRoot(document, <Root />)
}

main()
15 changes: 15 additions & 0 deletions playground/ssr-react-streaming/src/entry-server.tsx
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { IncomingMessage, OutgoingMessage } from 'node:http'
import ReactDOMServer from 'react-dom/server'
import { Root } from './root'

export default async function handler(
_req: IncomingMessage,
res: OutgoingMessage,
) {
const assets = await import('virtual:assets-manifest' as any)
const htmlStream = ReactDOMServer.renderToPipeableStream(<Root />, {
bootstrapModules: assets.default.bootstrapModules,
})
res.setHeader('content-type', 'text/html;charset=utf-8')
htmlStream.pipe(res)
}
60 changes: 60 additions & 0 deletions playground/ssr-react-streaming/src/root.tsx
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import * as React from 'react'

export function Root() {
return (
<html>
<head>
<title>Streaming</title>
</head>
<body>
<h4>Streaming</h4>
<TestSuspense />
<Hydrated />
<Counter />
</body>
</html>
)
}

function Counter() {
const [count, setCount] = React.useState(0)
return (
<button data-testid="counter" onClick={() => setCount((c) => c + 1)}>
Counter: {count}
</button>
)
}

function Hydrated() {
const hydrated = React.useSyncExternalStore(
React.useCallback(() => () => {}, []),
() => true,
() => false,
)
return <div data-testid="hydrated">[hydrated: {hydrated ? 1 : 0}]</div>
}

function TestSuspense() {
const context = React.useState(() => ({}))[0]
return (
<div data-testid="suspense">
<React.Suspense fallback={<div>suspense-fallback</div>}>
<Sleep context={context} />
</React.Suspense>
</div>
)
}

// use weak map to suspend for each server render
const sleepPromiseMap = new WeakMap<object, Promise<void>>()

function Sleep(props: { context: object }) {
if (typeof document !== 'undefined') {
return <div>suspense-resolved</div>
}
if (!sleepPromiseMap.has(props.context)) {
sleepPromiseMap.set(props.context, new Promise((r) => setTimeout(r, 1000)))
}
React.use(sleepPromiseMap.get(props.context))
return <div>suspense-resolved</div>
}
14 changes: 14 additions & 0 deletions playground/ssr-react-streaming/tsconfig.json
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "bundler",
"skipLibCheck": true,
"noEmit": true,
"jsx": "react-jsx",
"types": ["vite/client"],
"paths": {
"~utils": ["../test-utils.ts"]
}
}
}
123 changes: 123 additions & 0 deletions playground/ssr-react-streaming/vite.config.ts
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import path from 'node:path'
import fs from 'node:fs'
import type { Manifest } from 'vite'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

const CLIENT_ENTRY = path.join(import.meta.dirname, 'src/entry-client.jsx')
const SERVER_ENTRY = path.join(import.meta.dirname, 'src/entry-server.jsx')

export default defineConfig({
appType: 'custom',
build: {
minify: false,
},
environments: {
client: {
build: {
manifest: true,
outDir: 'dist/client',
rollupOptions: {
input: { index: CLIENT_ENTRY },
},
},
},
ssr: {
build: {
outDir: 'dist/server',
rollupOptions: {
input: { index: SERVER_ENTRY },
},
},
},
},
plugins: [
react(),
{
name: 'ssr-middleware',
configureServer(server) {
return () => {
server.middlewares.use(async (req, res, next) => {
try {
const mod = await server.ssrLoadModule(SERVER_ENTRY)
await mod.default(req, res)
} catch (e) {
next(e)
}
})
}
},
async configurePreviewServer(server) {
const mod = await import(
new URL('dist/server/index.js', import.meta.url).toString()
)
return () => {
server.middlewares.use(async (req, res, next) => {
try {
await mod.default(req, res)
} catch (e) {
next(e)
}
})
}
},
},
{
name: 'virtual-browser-entry',
resolveId(source) {
if (source === 'virtual:browser-entry') {
return '0円' + source
}
},
load(id) {
if (id === '0円virtual:browser-entry') {
if (this.environment.mode === 'dev') {
// ensure react hmr global before running client entry on dev.
// vite prepends base via import analysis, so we only need `/@react-refresh`.
return (
react.preambleCode.replace('__BASE__', '/') +
`import(${JSON.stringify(CLIENT_ENTRY)})`
)
}
}
},
},
{
name: 'virtual-assets-manifest',
resolveId(source) {
if (source === 'virtual:assets-manifest') {
return '0円' + source
}
},
load(id) {
if (id === '0円virtual:assets-manifest') {
let bootstrapModules: string[] = []
if (this.environment.mode === 'dev') {
bootstrapModules = ['/@id/__x00__virtual:browser-entry']
} else {
const manifest: Manifest = JSON.parse(
fs.readFileSync(
path.join(
import.meta.dirname,
'dist/client/.vite/manifest.json',
),
'utf-8',
),
)
const entry = Object.values(manifest).find(
(v) => v.name === 'index' && v.isEntry,
)!
bootstrapModules = [`/${entry.file}`]
}
return `export default ${JSON.stringify({ bootstrapModules })}`
}
},
},
],
builder: {
async buildApp(builder) {
await builder.build(builder.environments.client)
await builder.build(builder.environments.ssr)
},
},
})
19 changes: 19 additions & 0 deletions pnpm-lock.yaml
View file Open in desktop

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

AltStyle によって変換されたページ (->オリジナル) /