renderStreaming

用于 React v18+ Streaming SSR 渲染出可读流, 配合 createRequestHandler 使用

使用

src/entry.server.tsx
import {
  renderStreaming,
  createRequestHandler,
} from '@modern-js/runtime/ssr/server';

const handleRequest = async (request, ServerRoot, options) => {
  const stream = await renderStreaming(request, <ServerRoot />, options);

  return new Response(stream, {
    headers: {
      'content-type': 'text/html; charset=utf-8',
    },
  });
};

export default createRequestHandler(handleRequest);

函数签名

export type RenderStreaming = (
  request: Request,
  serverRoot: React.ReactElement,
  optinos: RenderOptions,
) => Promise<ReadableStream>;

示例

src/entry.server.tsx
import {
  renderStreaming,
  createRequestHandler,
} from '@modern-js/runtime/ssr/server';

const handleRequest = async (request, ServerRoot, options) => {
  // do something before render
  const stream = await renderStreaming(request, <ServerRoot />, options);

  // docs: https://developer.mozilla.org/en-US/docs/Web/API/TransformStream
  const transformStream = new TransformStream({
    transform(chunk, controller) {
      // do some transform
    },
  });

  stream.pipeThrough(transformStream);

  return new Response(transformStream.readable, {
    headers: {
      'content-type': 'text/html; charset=utf-8',
    },
  });
};

export default createRequestHandler(handleRequest);