Skip to content

Commit

Permalink
add pre rendering support (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
rphlmr authored Dec 20, 2024
1 parent 7998b7d commit 2e45d45
Show file tree
Hide file tree
Showing 50 changed files with 1,537 additions and 403 deletions.
38 changes: 30 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -645,17 +645,39 @@ Cloudflare requires a different approach to WebSockets, based on Durable Objects
>
> Work in progress on Cloudflare team: https://github.com/flarelabs-net/vite-plugin-cloudflare
### Migrate from v1
## Pre-rendering
You should be able to use pre-rendering with this package.
> [!TIP]
> Check this [example](./examples/node/with-pre-render/) to see how to use it.
> [!IMPORTANT]
> You need to add the `serverBuildFile` option to your `react-router.config.ts` file.
>
> The file path is fixed to `assets/server-build.js`.
Add the prerender option to your `react-router.config.ts`
```ts
import type { Config } from "@react-router/dev/config";
export default {
serverBuildFile: "assets/server-build.js", // 🚨 Dont forget this
prerender: ["/"],
} satisfies Config;
```
## Migrate from v1
_You should not expect any breaking changes._
#### Install the latest version
### Install the latest version
```bash
npm install react-router-hono-server@latest
```
#### Create the server file
##### Option 1 - You previously had all your server code in `app/entry.server.tsx`
### Create the server file
#### Option 1 - You previously had all your server code in `app/entry.server.tsx`
```bash
touch app/server.ts
```
Expand All @@ -664,7 +686,7 @@ or
npx react-router-hono-server reveal file
```
##### Option 2 - You previously had your server code in a `server` folder
#### Option 2 - You previously had your server code in a `server` folder
```bash
mkdir app/server
touch app/server/index.ts
Expand All @@ -674,7 +696,7 @@ or
npx react-router-hono-server reveal folder
```
#### Move your server code
### Move your server code
Move your previous server code to the new file you created in the previous step.
> [!NOTE]
Expand All @@ -693,7 +715,7 @@ We now use the Vite virtual import `virtual:react-router/server-build` to load t
> export default await createHonoServer({/* other options */});
> ```
#### Update your `vite.config.ts`
### Update your `vite.config.ts`
> [!IMPORTANT]
> `devServer` is now `reactRouterHonoServer`.
Expand All @@ -710,7 +732,7 @@ If you used this hook for Sentry, check this [example](./examples/node/with-sent
If you used a custom `buildDirectory` option, check this [example](./examples/node/custom-build/react-router.config.ts) to see how to migrate.
#### Update your package.json scripts
### Update your package.json scripts
```json
"scripts": {
"build": "react-router build",
Expand Down
80 changes: 80 additions & 0 deletions examples/bun/with-pre-render/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* This is intended to be a basic starting point for linting in your app.
* It relies on recommended configs out of the box for simplicity, but you can
* and should modify this configuration to best suit your team's needs.
*/

/** @type {import('eslint').Linter.Config} */
module.exports = {
root: true,
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
env: {
browser: true,
commonjs: true,
es6: true,
},
ignorePatterns: ["!**/.server", "!**/.client"],

// Base config
extends: ["eslint:recommended"],

overrides: [
// React
{
files: ["**/*.{js,jsx,ts,tsx}"],
plugins: ["react", "jsx-a11y"],
extends: [
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"plugin:react-hooks/recommended",
"plugin:jsx-a11y/recommended",
],
settings: {
react: {
version: "detect",
},
formComponents: ["Form"],
linkComponents: [
{ name: "Link", linkAttribute: "to" },
{ name: "NavLink", linkAttribute: "to" },
],
"import/resolver": {
typescript: {},
},
},
},

// Typescript
{
files: ["**/*.{ts,tsx}"],
plugins: ["@typescript-eslint", "import"],
parser: "@typescript-eslint/parser",
settings: {
"import/internal-regex": "^~/",
"import/resolver": {
node: {
extensions: [".ts", ".tsx"],
},
typescript: {
alwaysTryTypes: true,
},
},
},
extends: ["plugin:@typescript-eslint/recommended", "plugin:import/recommended", "plugin:import/typescript"],
},

// Node
{
files: [".eslintrc.cjs"],
env: {
node: true,
},
},
],
};
5 changes: 5 additions & 0 deletions examples/bun/with-pre-render/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules

/.cache
/build
.env
36 changes: 36 additions & 0 deletions examples/bun/with-pre-render/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Welcome to Remix + Vite!

📖 See the [Remix docs](https://remix.run/docs) and the [Remix Vite docs](https://remix.run/docs/en/main/guides/vite) for details on supported features.

## Development

Run the Vite dev server:

```shellscript
npm run dev
```

## Deployment

First, build your app for production:

```sh
npm run build
```

Then run the app in production mode:

```sh
npm start
```

Now you'll need to pick a host to deploy it to.

### DIY

If you're familiar with deploying Node applications, the built-in Remix app server is production-ready.

Make sure to deploy the output of `npm run build`

- `build/server`
- `build/client`
3 changes: 3 additions & 0 deletions examples/bun/with-pre-render/app/components/input.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function Input(props: React.ComponentPropsWithoutRef<"input">) {
return <input type="text" placeholder="Input" {...props} />;
}
28 changes: 28 additions & 0 deletions examples/bun/with-pre-render/app/root.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { LinksFunction } from "react-router";
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router";
import styles from "~/styles/tailwind.css?url";

export const links: LinksFunction = () => [{ rel: "stylesheet", href: styles }];

export function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
<link rel="stylesheet" href={styles} />
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
</body>
</html>
);
}

export default function App() {
return <Outlet />;
}
4 changes: 4 additions & 0 deletions examples/bun/with-pre-render/app/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { RouteConfig } from "@react-router/dev/routes";
import { flatRoutes } from "@react-router/fs-routes";

export default flatRoutes() satisfies RouteConfig;
60 changes: 60 additions & 0 deletions examples/bun/with-pre-render/app/routes/_index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { useState } from "react";
import { useRevalidator } from "react-router";
import { Input } from "~/components/input";
import { getPublic } from "~/utils/.client/public";
import { getCommon } from "~/utils/.common/common";
import { getSecret } from "~/utils/.server/secret";
import { getEnv } from "~/utils/env.server";
import dbLogo from "/images/database.svg";
import type { Route } from "./+types/_index";

export function loader() {
console.log(getSecret(), getCommon());
return {
env: getEnv(),
};
}

export async function clientLoader({ serverLoader }: Route.ClientLoaderArgs) {
console.log(getPublic(), getCommon());
return {
...(await serverLoader()),
};
}

clientLoader.hydrate = true;

export default function Index({ loaderData: data }: Route.ComponentProps) {
const [value, setValue] = useState("");
console.log("dbLogo", dbLogo);
console.log("value", value);
const { revalidate } = useRevalidator();
return (
<div className="min-h-screen bg-gray-100 flex flex-col items-center justify-center">
<button type="button" onClick={revalidate} className="flex items-center gap-2">
<img src={dbLogo} alt="Database" />
Revalidate
</button>
<input />
<Input value={value} onChange={(e) => setValue(e.target.value)} />
<div className="mt-8 w-full max-w-4xl overflow-x-auto">
<table className="w-full border-collapse bg-gray-100 shadow-md rounded-lg">
<thead>
<tr className="bg-gray-200">
<th className="px-6 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">Key</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">Value</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{Object.entries(data.env).map(([key, value]) => (
<tr key={key} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{key}</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{value ?? "-"}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
26 changes: 26 additions & 0 deletions examples/bun/with-pre-render/app/routes/defer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import React from "react";
import { Await, useLoaderData } from "react-router";
import { Route } from "./+types/defer";

async function getProjectLocation() {
return new Promise((resolve) => setTimeout(() => resolve("user/project"), 2000)) as Promise<string>;
}

export async function loader() {
return {
project: getProjectLocation(),
};
}

export default function ProjectRoute({ loaderData }: Route.ComponentProps) {
return (
<main>
<h1>Let's locate your project</h1>
<React.Suspense fallback={<p>Loading project location...</p>}>
<Await resolve={loaderData.project} errorElement={<p>Error loading project location!</p>}>
{(location) => <p>Your project is at {location}.</p>}
</Await>
</React.Suspense>
</main>
);
}
4 changes: 4 additions & 0 deletions examples/bun/with-pre-render/app/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// generated by react-router-hono-server/dev
import { createHonoServer } from "react-router-hono-server/bun";

export default await createHonoServer();
3 changes: 3 additions & 0 deletions examples/bun/with-pre-render/app/styles/tailwind.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
3 changes: 3 additions & 0 deletions examples/bun/with-pre-render/app/utils/.client/public.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function getPublic() {
return "public";
}
3 changes: 3 additions & 0 deletions examples/bun/with-pre-render/app/utils/.common/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function getCommon() {
return "common";
}
3 changes: 3 additions & 0 deletions examples/bun/with-pre-render/app/utils/.server/secret.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function getSecret() {
return "secret";
}
3 changes: 3 additions & 0 deletions examples/bun/with-pre-render/app/utils/env.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function getEnv() {
return { ...process.env };
}
43 changes: 43 additions & 0 deletions examples/bun/with-pre-render/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"name": "bun-with-pre-render",
"private": true,
"sideEffects": true,
"type": "module",
"scripts": {
"build": "react-router build",
"dev": "bunx --bun vite",
"lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .",
"start": "bun ./build/server/index.js",
"typecheck": "react-router typegen && tsc"
},
"dependencies": {
"@react-router/fs-routes": "^7.0.1",
"@react-router/node": "^7.0.1",
"isbot": "^4.1.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router": "^7.0.1",
"react-router-hono-server": "*"
},
"devDependencies": {
"@react-router/dev": "^7.0.1",
"@types/bun": "^1.1.14",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.0",
"@typescript-eslint/eslint-plugin": "^6.7.4",
"@typescript-eslint/parser": "^6.7.4",
"autoprefixer": "^10.4.20",
"esbuild": "^0.23.1",
"eslint": "^8.38.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.28.1",
"eslint-plugin-jsx-a11y": "^6.7.1",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"postcss": "^8.4.41",
"tailwindcss": "^3.4.7",
"typescript": "^5.7.2",
"vite": "^5.4.11",
"vite-tsconfig-paths": "^5.1.3"
}
}
Loading

0 comments on commit 2e45d45

Please sign in to comment.