deno を使って、 react の SSR(サーバーサイドレンダリング)を動かす方法です。
今回参考にした記事はこちら
Writing a React SSR app in Deno
https://dev.to/craigmorten/writing-a-react-ssr-app-in-deno-2m7
コードは上記サイトのそのまま引用しています。
まず適当なフォルダを作り、作業フォルダとします
% mkdir test_dino % cd test_dino
3つのファイルを作ります。
test_dino/app.tsx
import { React } from "./deps.ts";
declare global {
namespace JSX {
interface IntrinsicElements {
button: any;
div: any;
h1: any;
p: any;
}
}
}
const App = () => {
const [count, setCount] = (React as any).useState(0);
return (
<div>
<h1>Hello DenoLand!</h1>
<button onClick={() => setCount(count + 1)}>Click the 🦕</button>
<p>You clicked the 🦕 {count} times</p>
</div>
);
};
export default App;
test_dino/deps.tsx
export { default as React } from "https://dev.jspm.io/react@16.13.1";
export { default as ReactDOMServer } from "https://dev.jspm.io/react-dom@16.13.1/server";
export { opine } from "https://deno.land/x/opine@0.21.2/mod.ts";
test_dino/server.tsx
import {
opine,
React,
ReactDOMServer,
} from "./deps.ts";
import App from "./app.tsx";
const app = opine();
const browserBundlePath = "/browser.js";
const js =
`import React from "https://dev.jspm.io/react@16.13.1";\nimport ReactDOM from "https://dev.jspm.io/react-dom@16.13.1";\nconst App = ${App};\nReactDOM.hydrate(React.createElement(App), document.body);`;
const html =
`${
(ReactDOMServer as any).renderToString()
}`;
app.use(browserBundlePath, (req, res, next) => {
res.type("application/javascript").send(js);
});
app.use("/", (req, res, next) => {
res.type("text/html").send(html);
});
app.listen({ port: 3000 });
console.log("React SSR App listening on port 3000");
以下で実行します
% deno run --allow-net --allow-read server.tsx
React SSR App listening on port 3000
と表示されて
ブラウザで http://localhost:3000 にアクセスして
以下のように表示されれば成功です!

Deno のオススメ本
Introducing Deno: A First Look at the Newest JavaScript Runtime
Beginning Deno Development
The Deno Handbook (Scots Gaelic Edition)


コメント