Skip to content

Commit

Permalink
🐛 FIX: The buildDirectory option was not affecting the client base di…
Browse files Browse the repository at this point in the history
…rectory (#13)
  • Loading branch information
rphlmr authored Nov 4, 2024
1 parent c0e786e commit 32c7cc0
Show file tree
Hide file tree
Showing 24 changed files with 599 additions and 11 deletions.
80 changes: 80 additions & 0 deletions examples/remix-unstable-custom-build/.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,
},
},
],
};
6 changes: 6 additions & 0 deletions examples/remix-unstable-custom-build/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules

/.cache
/build
/dist
.env
36 changes: 36 additions & 0 deletions examples/remix-unstable-custom-build/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`
18 changes: 18 additions & 0 deletions examples/remix-unstable-custom-build/app/entry.client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* By default, Remix will handle hydrating your app on the client for you.
* You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨
* For more information, see https://remix.run/file-conventions/entry.client
*/

import { RemixBrowser } from "@remix-run/react";
import { StrictMode, startTransition } from "react";
import { hydrateRoot } from "react-dom/client";

startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<RemixBrowser />
</StrictMode>
);
});
123 changes: 123 additions & 0 deletions examples/remix-unstable-custom-build/app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/**
* By default, Remix will handle generating the HTTP Response for you.
* You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨
* For more information, see https://remix.run/file-conventions/entry.server
*/

import { PassThrough } from "node:stream";
import type { AppLoadContext, EntryContext } from "@remix-run/node";
import { createReadableStreamFromReadable } from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
import { isbot } from "isbot";
import { renderToPipeableStream } from "react-dom/server";

export * from "./server";

const ABORT_DELAY = 5_000;

export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
// This is ignored so we can keep it in the template for visibility. Feel
// free to delete this parameter in your app if you're not using it!
// eslint-disable-next-line @typescript-eslint/no-unused-vars
loadContext: AppLoadContext
) {
return isbot(request.headers.get("user-agent") || "")
? handleBotRequest(request, responseStatusCode, responseHeaders, remixContext)
: handleBrowserRequest(request, responseStatusCode, responseHeaders, remixContext);
}

function handleBotRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
return new Promise((resolve, reject) => {
let shellRendered = false;
const { pipe, abort } = renderToPipeableStream(
<RemixServer context={remixContext} url={request.url} abortDelay={ABORT_DELAY} />,
{
onAllReady() {
shellRendered = true;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);

responseHeaders.set("Content-Type", "text/html");

resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
})
);

pipe(body);
},
onShellError(error: unknown) {
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
}
},
}
);

setTimeout(abort, ABORT_DELAY);
});
}

function handleBrowserRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
return new Promise((resolve, reject) => {
let shellRendered = false;
const { pipe, abort } = renderToPipeableStream(
<RemixServer context={remixContext} url={request.url} abortDelay={ABORT_DELAY} />,
{
onShellReady() {
shellRendered = true;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);

responseHeaders.set("Content-Type", "text/html");

resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
})
);

pipe(body);
},
onShellError(error: unknown) {
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
}
},
}
);

setTimeout(abort, ABORT_DELAY);
});
}
28 changes: 28 additions & 0 deletions examples/remix-unstable-custom-build/app/root.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { LinksFunction } from "@remix-run/node";
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "@remix-run/react";
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 />;
}
54 changes: 54 additions & 0 deletions examples/remix-unstable-custom-build/app/routes/_index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { type ClientLoaderFunctionArgs, useLoaderData, useRevalidator } from "@remix-run/react";
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";

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

export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {
console.log(getPublic(), getCommon());
return {
...(await serverLoader<typeof loader>()),
};
}

clientLoader.hydrate = true;

export default function Index() {
const data = useLoaderData<typeof loader>();
console.log(dbLogo);
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>
<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>
);
}
12 changes: 12 additions & 0 deletions examples/remix-unstable-custom-build/app/server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { createHonoServer } from "react-router-hono-server/node";
import { exampleMiddleware } from "./middleware";

export const server = await createHonoServer({
buildDirectory: "dist",
configure(server) {
server.use("*", exampleMiddleware());
},
listeningListener(info) {
console.log(`Server is listening on http://localhost:${info.port}`);
},
});
8 changes: 8 additions & 0 deletions examples/remix-unstable-custom-build/app/server/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createMiddleware } from "hono/factory";

export function exampleMiddleware() {
return createMiddleware(async (c, next) => {
console.log("accept-language", c.req.header("accept-language"));
return next();
});
}
3 changes: 3 additions & 0 deletions examples/remix-unstable-custom-build/app/styles/tailwind.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function getPublic() {
return "public";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function getCommon() {
return "common";
}
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/remix-unstable-custom-build/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 };
}
Loading

0 comments on commit 32c7cc0

Please sign in to comment.