HonoH
Hono9mo ago
Vikash

How to build for React + Vite + Cloudflare worker?

I am using this example provided by Cloudflare for Vite + React + Hono https://github.com/cloudflare/templates/tree/main/vite-react-template which works fine if I use it as-is.

But I need to change the static
index.html
to index.tsx to serve the initial html by hono to add title, description, meta tags etc. based on the pathname.

So, I changed the
index.html
with index.tsx

import { Hono } from "hono";

const app = new Hono();

const routes = app.get("/api/clock", (c) => {
  return c.json({
    time: new Date().toLocaleTimeString(),
  });
});

export type AppType = typeof routes;

app.get("/", (c) => {
  return c.html(
    `<html lang="en">
      <head>
        <meta charset="UTF-8" />
        <link rel="icon" type="image/svg+xml" href="/vite.svg" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Vite + React + Hono</title>        
      </head>
      <body>
        <div id="root"/>
        <script type="module" src="/src/app/main.tsx"></script>
      </body>
    </html>`
  );
});

export default app;


And, I also tried to change the vite config to add build from import build from "@hono/vite-build/cloudflare-workers" but it doesn't work.

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { cloudflare } from "@cloudflare/vite-plugin";
import path from "path";
import tailwindcss from "@tailwindcss/vite";
import devServer from "@hono/vite-dev-server";
import build from "@hono/vite-build/cloudflare-workers";

export default defineConfig({
  plugins: [
    react(),
    cloudflare(),
    tailwindcss(),
    build({
      entry: "index.tsx",
    }),
    devServer({
      entry: "index.tsx",
    }),
  ],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
});
GitHub
Templates for Cloudflare Workers. Contribute to cloudflare/templates development by creating an account on GitHub.
Was this page helpful?