Open1

Suspense, RSC (React Server Components) 試すメモ、pages版

knaka Tech-Blogknaka Tech-Blog

概要

React Server Componentsを、表示するメモになります。

  • Suspense使います
  • RSCは、開発段階らしいので。お試しとなります
  • esbuildで、ビルドします
  • CF-pagesに、デプロイ

[ 公開: 2024/01/08 ]


環境

  • cloudflare pages
  • esbuild
  • hono

参考


試したコード

https://github.com/kuc-arc-f/rsc-pages-4


  • index.tsx
  • renderToReadableStream で、コンポーネント送信できそうでした
index.tsx

const App = () => (
  <Suspense fallback={<div>Loading 3 sec...</div>}>
    <div>Hello</div>
  </Suspense>
);
/*
*/
//
app.get('/', async (c) => {
	return c.html(`
	<!DOCTYPE html>
	<html>
	<head>
		<title>React Server Components from Scratch</title>
		<script src="https://cdn.tailwindcss.com"></script>
	</head>
	<body>
		<div id="root"></div>
    <script src="/static/rsc.js"></script>
	</body>
	</html>
	`);
});
/*
*/
app.get("/rsc", async (c) => {
  const stream = await renderToReadableStream(<App />);
//console.log(stream);
  return new Response(stream);
});

  • 関連のパス
  • / : 開く画面
  • /rsc : RSC 呼び出す、エンドポイント

  • rsc.ts
rsc.ts

import { createRoot } from 'react-dom/client';
import { createFromFetch } from 'react-server-dom-webpack/client';

window.__webpack_require__ = async (id) => {
  return import(id);
};
const root = createRoot(document.getElementById('root'));
createFromFetch(fetch('/rsc')).then(comp => {
  root.render(comp);
})

  • package.json
{
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build && vite build --mode client",
    "preview": "npx wrangler pages dev dist --compatibility-date=2024-01-01",
    "deploy": "$npm_execpath run build && wrangler pages deploy dist"
  },
  "dependencies": {
    "es-module-lexer": "^1.3.1",
		"esbuild": "^0.17.14",
    "hono": "^3.11.11",
    "react": "18.3.0-next-3706edb81-20230308",
		"react-dom": "18.3.0-next-3706edb81-20230308",
		"react-server-dom-webpack": "0.0.0-experimental-41b4714f1-20230328"
  },
  "devDependencies": {
    "@cloudflare/workers-types": "^4.20231218.0",
    "@hono/vite-cloudflare-pages": "^0.1.2",
    "@hono/vite-dev-server": "^0.3.1",
    "@types/react": "^18.0.31",
		"@types/react-dom": "^18.0.11",
    "vite": "^5.0.10",
    "wrangler": "^3.22.0"
  }
}


  • install, build, preview
* npm i --legacy-peer-deps
* yarn build
* npx esbuild --bundle ./src/rsc.ts --format=esm --minify --outfile=./dist/static/rsc.js
* yarn preview
  • deploy
npx wrangler pages deploy dist