2
3

More than 3 years have passed since last update.

DenoでpreactのコンポーネントをSSRする

Posted at

はじめに

@isihigameKoudaiさんの DenoでReact Server Side Renderingした話 の記事に触発されて、DenoでpreactコンポーネントのSSRをやってみました。

必要なもの

preactのコンポーネントをSSRする

まず、mod.tsという名前で以下のようなファイルを用意します。

mod.ts
import { html } from "https://cdn.skypack.dev/htm@v3.0.4/preact/standalone.module.js";
import renderToString from "https://cdn.skypack.dev/preact-render-to-string@v5.1.10";
import { serve } from "https://deno.land/std@v0.61.0/http/server.ts";

// コンポーネント
const App = () => html`
  <div>
    Hello world!
  </div>
`;

// HTTPサーバを起動
const server = serve({ port: 3000 });
for await (const req of server) {
  req.respond({
    body: renderToString(html`
      <html>
        <head>
          <title>Hello world</title>
          <meta charset="utf-8" />
        </head>
        <body>
          <${App} />
        </body>
      </html>
    `)
  });
}

次に、以下のコマンドでmod.tsを実行し、HTTPサーバを起動します。

$ deno run --allow-net mod.ts

サーバが起動したら、curlでリクエストを送信します。

$ curl http://localhost:3000
<html><head><title>Hello world</title><meta charset="utf-8" /></head><body><div>Hello world!</div></body></html>

HTMLが表示されれば成功です!

おわりに

この記事は以下のサイトを参考にしました :bow:

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3