docs: make 2.x the default version (#3369)
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
---
|
||||
description: |
|
||||
Add a global app wrapper to provide common meta tags or context for application routes.
|
||||
---
|
||||
|
||||
The app wrapper component is a Preact component that represents the outer
|
||||
structure of the HTML document, typically up until the `<body>`-tag. It is only
|
||||
rendered on the server and never on the client. The passed `Component` value
|
||||
represents the children of this component.
|
||||
|
||||
```tsx main.tsx
|
||||
function AppWrapper({ Component }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>My App</title>
|
||||
</head>
|
||||
<body>
|
||||
<Component />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
app.appWrapper(AppWrapper);
|
||||
```
|
||||
|
||||
Every [`ctx.render()`](/docs/concepts/context#render-1) call will include the
|
||||
app wrapper component by default, unless opted out.
|
||||
|
||||
Note that only one app wrapper component is supported per
|
||||
[`App`](/docs/concepts/app) instance.
|
||||
@@ -0,0 +1,195 @@
|
||||
---
|
||||
description: |
|
||||
The Builder class is used to generate optimized assets for production.
|
||||
---
|
||||
|
||||
> [warn]: The `Builder` class was used during the alpha phase of Fresh 2 before
|
||||
> the Fresh vite plugin was released. You can skip this page if you're using
|
||||
> vite.
|
||||
|
||||
The `Builder` class is used to generate production assets of your app. You'll
|
||||
typically find it being created inside your project's `dev.ts` file.
|
||||
|
||||
```ts dev.ts
|
||||
import { Builder } from "fresh/dev";
|
||||
|
||||
const builder = new Builder({ target: "safari12" });
|
||||
|
||||
if (Deno.args.includes("build")) {
|
||||
// This creates a production build
|
||||
await builder.build();
|
||||
} else {
|
||||
// This starts a development server with live reload
|
||||
await builder.listen(() => import("./main.ts"));
|
||||
}
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
You can customize the builder by passing options.
|
||||
|
||||
```ts dev.ts
|
||||
const builder = new Builder({
|
||||
// Browser target for generated code. Maps to https://esbuild.github.io/api/#target
|
||||
target?: string | string[];
|
||||
// The root directory of the project. All other paths will be resolved
|
||||
// against this if they're relative. (Default: `Deno.cwd()`)
|
||||
root?: string;
|
||||
// The path to your server entry point. (Default: `<root>/main.ts`)
|
||||
serverEntry?: string;
|
||||
// Where to write generated files when doing a production build.
|
||||
// (default: `<root>/_fresh/`)
|
||||
outDir?: string;
|
||||
// Path to static file directory. (Default: `<root>/static/`)
|
||||
staticDir?: string;
|
||||
// Path to island directory. (Default: `<root>/islands`)
|
||||
islandDir?: string;
|
||||
// Path to routes directory. (Default: `<root>/routes`)
|
||||
routeDir?: string;
|
||||
// File paths which should be ignored
|
||||
ignore?: RegExp[];
|
||||
// Optionally generate production source maps
|
||||
// See https://esbuild.github.io/api/#source-maps
|
||||
sourceMap?: {
|
||||
kind?: boolean | 'linked' | 'inline' | 'external' | 'both';
|
||||
sourceRoot?: string;
|
||||
sourcesContent?: boolean;
|
||||
};
|
||||
})
|
||||
```
|
||||
|
||||
## Registering islands
|
||||
|
||||
The builder is where you'll register files that contain islands. This is the
|
||||
same API that Fresh uses internally.
|
||||
|
||||
```ts dev.ts
|
||||
const builder = new Builder();
|
||||
|
||||
// Path to local island
|
||||
builder.registerIsland("path/to/my/Island.tsx");
|
||||
// File urls work too
|
||||
builder.registerIsland("file:///path/to/my/Island.tsx");
|
||||
// Also islands from jsr
|
||||
builder.registerIsland("jsr:@marvinh-test/fresh-island");
|
||||
```
|
||||
|
||||
## Adding build plugins
|
||||
|
||||
The `Builder` has a very simple processing mechanism for static files.
|
||||
|
||||
```ts dev.ts
|
||||
builder.onTransformStaticFile({
|
||||
pluginName: "My cool plugin",
|
||||
filter: /\.css$/,
|
||||
}, (args) => {
|
||||
// Prepend `body { background: red }` to every `.css` file
|
||||
const code = `body { background: red } ${args.text}`;
|
||||
|
||||
return {
|
||||
content: code,
|
||||
map: undefined, // Optional: source maps
|
||||
};
|
||||
});
|
||||
```
|
||||
|
||||
> [info]: Only static files in `static/` or the value you set `staticDir` to
|
||||
> will be processed. The builder won't process anything else.
|
||||
|
||||
## Testing
|
||||
|
||||
Testing applications with the `Builder` class involves creating a build snapshot
|
||||
and assigning that to each app instance.
|
||||
|
||||
```ts my-app.test.ts
|
||||
// Best to do this once instead of for every test case for
|
||||
// performance reasons.
|
||||
const builder = new Builder();
|
||||
const applySnapshot = await builder.build({ snapshot: "memory" });
|
||||
|
||||
function testApp() {
|
||||
const app = new App()
|
||||
.get("/", () => new Response("hello"))
|
||||
.fsRoutes();
|
||||
|
||||
// Applies build snapshot to this app instance.
|
||||
applySnapshot(app);
|
||||
return app;
|
||||
}
|
||||
|
||||
Deno.test("My Test", async () => {
|
||||
const handler = testApp().handler();
|
||||
|
||||
const response = await handler(new Request("http://localhost"));
|
||||
const text = await response.text();
|
||||
|
||||
if (text !== "hello") {
|
||||
throw new Error("fail");
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Tailwindcss
|
||||
|
||||
[Tailwindcss](https://tailwindcss.com/) is a utility-first CSS framework that
|
||||
generates CSS out of the class names that are used in JSX. Since we use
|
||||
Tailwindcss ourselves here at Deno, Fresh ships with an official plugin for
|
||||
that.
|
||||
|
||||
### Usage
|
||||
|
||||
1. Set `nodeModulesDir` in `deno.json` to `"auto"` or `"manual"`
|
||||
|
||||
```diff deno.json
|
||||
{
|
||||
"name": "@example/my-cool-project"
|
||||
+ "nodeModulesDir": "auto",
|
||||
"imports": {
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. Run `deno install jsr:@fresh/plugin-tailwind`
|
||||
3. Update `dev.ts`:
|
||||
|
||||
```diff dev.ts
|
||||
import { Builder } from "fresh/dev";
|
||||
+ import { tailwind } from "@fresh/plugin-tailwind";
|
||||
|
||||
const builder = new Builder();
|
||||
+ tailwind(builder);
|
||||
```
|
||||
|
||||
4. Add `@import "tailwindcss";` at the top of your main stylesheet.
|
||||
|
||||
For more information on how to use tailwindcss, check out
|
||||
[their documentation](https://tailwindcss.com/docs/styling-with-utility-classes).
|
||||
|
||||
### Options
|
||||
|
||||
You can customize the tailwind plugin via the following options:
|
||||
|
||||
```ts dev.ts
|
||||
tailwind(builder, app, {
|
||||
// Exclude certain files from processing
|
||||
exclude: ["/admin/**", "*.temp.css"],
|
||||
// Force optimization (defaults to production mode)
|
||||
optimize: true,
|
||||
// Exclude base styles
|
||||
base: null,
|
||||
});
|
||||
```
|
||||
|
||||
### Tailwindcss v3
|
||||
|
||||
If can't update to the current version of tailwindcss we have a dedicated
|
||||
`@fresh/plugin-tailwindcss-v3` plugin that uses tailwindcss v3. That way you can
|
||||
decided on your own when it's best to update to v4.
|
||||
|
||||
```ts dev.ts
|
||||
import { Builder } from "fresh/dev";
|
||||
import { tailwind } from "@fresh/plugin-tailwind-v3";
|
||||
|
||||
tailwind(builder, {});
|
||||
```
|
||||
@@ -0,0 +1,85 @@
|
||||
---
|
||||
description: |
|
||||
Define helpers are a less TypeScripty way to declare middlewares, routes and layouts
|
||||
---
|
||||
|
||||
Define helpers can be used to shorten the amount of types you have to type
|
||||
yourself in code. They are entirely optional as some developers prefer the
|
||||
expliciteness of types, other's like the convenience of `define.*` helpers.
|
||||
|
||||
Without define helpers:
|
||||
|
||||
```ts util.ts
|
||||
export interface State {
|
||||
foo: string;
|
||||
}
|
||||
```
|
||||
|
||||
```ts middleware.ts
|
||||
import type { State } from "./util.ts";
|
||||
|
||||
export async function myMiddleware(ctx: Context<State>): Promise<Response> {
|
||||
return new Response("hello " + ctx.state.foo);
|
||||
}
|
||||
|
||||
export async function otherMiddleware(ctx: Context<State>): Promise<Response> {
|
||||
return new Response("other " + ctx.state.foo);
|
||||
}
|
||||
```
|
||||
|
||||
With define helpers:
|
||||
|
||||
```ts util.ts
|
||||
import { createDefine } from "fresh";
|
||||
|
||||
// Setup, do this once in a file and import it everywhere else.
|
||||
export const define = createDefine<{ foo: string }>();
|
||||
```
|
||||
|
||||
```ts middleware.ts
|
||||
import { define } from "./util.ts";
|
||||
|
||||
// Usage
|
||||
export const myMiddleware = define.middleware((ctx) => {
|
||||
return new Response("hello " + ctx.state.foo);
|
||||
});
|
||||
|
||||
export const otherMiddleware = define.middleware((ctx) => {
|
||||
return new Response("other " + ctx.state.foo);
|
||||
});
|
||||
```
|
||||
|
||||
## File routes
|
||||
|
||||
The `define.*` helpers include a `define.handler()` and `define.page()` function
|
||||
to make it easy for TypeScript to establish a relation between the two. That way
|
||||
when you can pass data from the handler to the component in a type-safe way.
|
||||
|
||||
```tsx routes/index.tsx
|
||||
export const handler = define.handlers({
|
||||
GET(ctx) {
|
||||
return { data: { foo: "Deno" } };
|
||||
},
|
||||
});
|
||||
|
||||
// When you type `props.data.*` you'll get autocompletion
|
||||
export default define.page<typeof handler>((props) => {
|
||||
return (
|
||||
<div>
|
||||
<h1>I like {props.data.foo}</h1>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
There is also a `define.layout()` helper for layouts:
|
||||
|
||||
```tsx
|
||||
export default define.layout((props) => {
|
||||
return (
|
||||
<div>
|
||||
<h1>I like {props.state.foo}</h1>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
description: |
|
||||
Error pages can be used to customize the page that is shown when an error occurs in the application.
|
||||
---
|
||||
|
||||
Environment variables in Deno are typically read via `Deno.env.get()` or
|
||||
`process.env.*` calls or via an `.env` file if the `--env-file` flag is used,
|
||||
see
|
||||
[how to use Environment Variables in Deno](https://docs.deno.com/runtime/reference/env_variables/).
|
||||
|
||||
On top of that Fresh automatically inlines all environment variables whose names
|
||||
start with `FRESH_PUBLIC_` during bundling of islands.
|
||||
|
||||
> [info]: This inlining step occurs when building the app (`deno task build`).
|
||||
> Environment variables inside islands cannot be read at runtime.
|
||||
|
||||
Example:
|
||||
|
||||
```sh Terminal
|
||||
$ FRESH_PUBLIC_FOO=bar deno task dev
|
||||
```
|
||||
|
||||
```tsx
|
||||
export function MyIsland() {
|
||||
const value = Deno.env.get("FRESH_PUBLIC_FOO");
|
||||
return <h1>{value}</h1>;
|
||||
}
|
||||
```
|
||||
|
||||
This code when bundled will be turned into this:
|
||||
|
||||
```tsx
|
||||
export function MyIsland() {
|
||||
const value = "bar";
|
||||
return <h1>{value}</h1>;
|
||||
}
|
||||
```
|
||||
|
||||
This way you can use specific environment variables in the browser.
|
||||
|
||||
> [warn]: To make inlining work the code needs to be analyzable by our plugins.
|
||||
> This means that not all forms of reading an environment variable in Deno are
|
||||
> supported, even if it's perfectly valid JavaScript code.
|
||||
>
|
||||
> ```ts MyIsland.tsx
|
||||
> // CORRECT
|
||||
> Deno.env.get("FRESH_PUBLIC_FOO");
|
||||
> process.env.FRESH_PUBLIC_FOO;
|
||||
>
|
||||
> // WRONG
|
||||
> const name = "FRESH_PUBLIC_FOO";
|
||||
> Deno.env.get(name);
|
||||
> process.env[name];
|
||||
>
|
||||
> // WRONG
|
||||
> const obj = Deno.env.toObject();
|
||||
> obj.FRESH_PUBLIC_FOO;
|
||||
> ```
|
||||
@@ -0,0 +1,102 @@
|
||||
---
|
||||
description: |
|
||||
Error pages can be used to customize the page that is shown when an error occurs in the application.
|
||||
---
|
||||
|
||||
Error pages are used to ensure that your app keeps working and display relevant
|
||||
feedback to the one who made the request.
|
||||
|
||||
Fresh supports two kind of error pages:
|
||||
|
||||
1. Generic error pages
|
||||
2. 404 Not found error pages
|
||||
|
||||
> [tip]: Be sure to return the appropriate
|
||||
> [HTTP Status](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status)
|
||||
> code. This makes it a lot easier for clients of your app to act appropriately.
|
||||
> It also makes it easier to find failed requests when going through traces.
|
||||
|
||||
## Generic error pages
|
||||
|
||||
To add an error page use [`app.onError()`](/docs/concepts/app#onerror).
|
||||
|
||||
```ts main.ts
|
||||
const app = new App()
|
||||
.onError("*", (ctx) => {
|
||||
console.log(`Error: ${ctx.error}`);
|
||||
return new Response("Oops!", { status: 500 });
|
||||
})
|
||||
.get("/thrower", () => {
|
||||
throw new Error("fail");
|
||||
});
|
||||
```
|
||||
|
||||
When you access `/thrower` the error will be caught and the `onError` callback
|
||||
will be invoked.
|
||||
|
||||
You can also nest error pages:
|
||||
|
||||
```ts main.ts
|
||||
const app = new App()
|
||||
// Top level error page
|
||||
.onError("*", (ctx) => {
|
||||
return new Response("Oops!", { status: 500 });
|
||||
})
|
||||
.onError("/foo/bar", (ctx) => {
|
||||
return new Response("nested error!", { status: 500 });
|
||||
})
|
||||
.get("/foo/bar/thrower", () => {
|
||||
throw new Error("fail");
|
||||
});
|
||||
```
|
||||
|
||||
## Not found error
|
||||
|
||||
Not found errors are often treated differently than generic errors. You can both
|
||||
treat them with the `.onError()` way, but by adding a specific `.notFound()`
|
||||
handler, Fresh ensures that every 404 error will invoke this callback.
|
||||
|
||||
```ts main.ts
|
||||
const app = new App()
|
||||
// Top level error page
|
||||
.notFound((ctx) => {
|
||||
return new Response("Page not found", { status: 404 });
|
||||
})
|
||||
.get("/", () => new Response("foo"));
|
||||
```
|
||||
|
||||
Accessing an unknown route like `/invalid` will trigger the `notFound`
|
||||
middleware. Contrary to generic error pages this handler cannot be nested.
|
||||
|
||||
## Throwing HTTP errors
|
||||
|
||||
If you need to bail out of execution and need to respond with a particular HTTP
|
||||
error code, you can use Fresh's `HttpError` class.
|
||||
|
||||
```ts middleware/auth.ts
|
||||
import { HttpError } from "fresh";
|
||||
|
||||
async function authMiddleware(ctx) {
|
||||
const user = ctx.state.user;
|
||||
|
||||
// Check if user is authenticated, throw 404 error if not
|
||||
if (!isAuthenticated(user)) {
|
||||
throw new HttpError(404);
|
||||
}
|
||||
|
||||
return await ctx.next();
|
||||
}
|
||||
```
|
||||
|
||||
You can check the status code of the thrown `HttpError` in your error handler:
|
||||
|
||||
```ts main.ts
|
||||
app.onError((ctx) => {
|
||||
if (ctx.error instanceof HttpError) {
|
||||
const status = ctx.error.status;
|
||||
return new Response("oops", { status });
|
||||
}
|
||||
|
||||
// ...
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,110 @@
|
||||
---
|
||||
description: |
|
||||
Robustly handle user inputs using HTML `<form>` elements client side, and form
|
||||
submission handlers server side.
|
||||
---
|
||||
|
||||
For stronger resiliency and user experience, Fresh relies on native browser
|
||||
support for form submissions with the HTML `<form>` element.
|
||||
|
||||
In the browser, a `<form>` submit will send an HTML action (usually `GET` or
|
||||
`POST`) to the server, which responds with a new page to render.
|
||||
|
||||
## POST request with `application/x-www-form-urlencoded`
|
||||
|
||||
Forms typically submit as a `GET` request with data encoded in the URL's search
|
||||
parameters, or as a `POST` request with either an
|
||||
`application/x-www-form-urlencoded` or `multipart/form-data` body.
|
||||
|
||||
This example demonstrates how to handle `application/x-www-form-urlencoded`
|
||||
`<form>` submissions:
|
||||
|
||||
```tsx routes/subscribe.tsx
|
||||
import { define } from "../utils.ts";
|
||||
|
||||
export const handlers = define.handlers({
|
||||
async GET(ctx) {
|
||||
return { data: {} };
|
||||
},
|
||||
async POST(ctx) {
|
||||
const form = await ctx.req.formData();
|
||||
const email = form.get("email")?.toString();
|
||||
|
||||
// Add email to list.
|
||||
|
||||
// Redirect user to thank you page.
|
||||
const headers = new Headers();
|
||||
headers.set("location", "/thanks-for-subscribing");
|
||||
return new Response(null, {
|
||||
status: 303, // See Other
|
||||
headers,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export default define.page<typeof handlers>(function Subscribe() {
|
||||
return (
|
||||
<>
|
||||
<form method="post">
|
||||
<input type="email" name="email" value="" />
|
||||
<button type="submit">Subscribe</button>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
When the user submits the form, Deno will retrieve the `email` value using the
|
||||
request's `formData()` method, add the email to a list, and redirect the user to
|
||||
a thank you page.
|
||||
|
||||
## Handling file uploads
|
||||
|
||||
File uploads can be handled in a very similar manner to the example above. Note
|
||||
that this time, we have to explicitly declare the form's encoding to be
|
||||
`multipart/form-data`.
|
||||
|
||||
```tsx routes/subscribe.tsx
|
||||
import { define } from "../utils.ts";
|
||||
|
||||
export const handler = define.handlers({
|
||||
async GET(ctx) {
|
||||
return { data: { message: null } };
|
||||
},
|
||||
async POST(ctx) {
|
||||
const form = await ctx.req.formData();
|
||||
const file = form.get("my-file") as File;
|
||||
|
||||
if (!file) {
|
||||
return { data: { message: "Please try again" } };
|
||||
}
|
||||
|
||||
const name = file.name;
|
||||
const contents = await file.text();
|
||||
|
||||
console.log(contents);
|
||||
|
||||
return { data: { message: `${name} uploaded!` } };
|
||||
},
|
||||
});
|
||||
|
||||
export default define.page<typeof handlers>(function Upload(props) {
|
||||
const { message } = props.data;
|
||||
return (
|
||||
<>
|
||||
<form method="post" encType="multipart/form-data">
|
||||
<input type="file" name="my-file" />
|
||||
<button type="submit">Upload</button>
|
||||
</form>
|
||||
{message ? <p>{message}</p> : null}
|
||||
</>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
## A note of caution
|
||||
|
||||
These examples are simplified to demonstrate how Deno and Fresh handle HTTP
|
||||
requests. In the Real World™, you'll want to validate your data (_especially the
|
||||
file type_) and protect against cross-site request forgery. Consider yourself
|
||||
warned.
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
description: Modify the document head in Fresh
|
||||
---
|
||||
|
||||
The
|
||||
[`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/head)-element
|
||||
is a crucial element in HTML to set metadata for a page. It allows you to:
|
||||
|
||||
- Set the document title with `<title>`
|
||||
- Specify page metadata with `<meta>`
|
||||
- Link to resources like stylesheets with `<link>`
|
||||
- Include JavaScript code with `<script>`
|
||||
|
||||
> [info]: The outer HTML structure including `<head>` is typically created
|
||||
> inside `_app.tsx`.
|
||||
|
||||
## Passing metadata from `ctx.state`
|
||||
|
||||
For simple scenarios passing metadata along from a handler or a middleware by
|
||||
writing to `ctx.state` is often sufficient.
|
||||
|
||||
```tsx routes/_app.tsx
|
||||
import { define } from "../util.ts";
|
||||
|
||||
export default define.page((ctx) => {
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>{ctx.state.title ?? "Welcome!"}</title>
|
||||
</head>
|
||||
<body>
|
||||
<ctx.Component />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
## Using the `<Head>`-component
|
||||
|
||||
For more complex scenarios, or to set page metadata from islands, Fresh ships
|
||||
with the `<Head>`-component.
|
||||
|
||||
> [info]: The `<Head>` component is not dynamic by default. It will not
|
||||
> automatically update the document title or other head elements on the client
|
||||
> side when component state changes. The head elements are set during server
|
||||
> rendering or initial page load.
|
||||
|
||||
```tsx routes/about.tsx
|
||||
import { Head } from "fresh/runtime";
|
||||
|
||||
export default define.page((ctx) => {
|
||||
return (
|
||||
<div>
|
||||
<Head>
|
||||
<title>About me</title>
|
||||
</Head>
|
||||
<h1>About me</h1>
|
||||
<p>I like Fresh!</p>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
### Avoiding duplicate tags
|
||||
|
||||
You might end up with duplicate tags, when multiple `<Head />` components are
|
||||
rendered on the same page. Fresh will employ the following strategies to find
|
||||
the matching element:
|
||||
|
||||
1. For `<title>` elements Fresh will set `document.title` directly
|
||||
2. Check if an element with the same `key` exists
|
||||
3. Check if an element with the same `id` attribute
|
||||
4. Only for `<meta>` elements: Check if there is a `<meta>` element with the
|
||||
same `name` attribute
|
||||
5. No matching element was found, Fresh will create a new one and append it to
|
||||
`<head>`
|
||||
|
||||
> [info]: The `<title>`-tag is automatically deduplicated, even without a `key`
|
||||
> prop.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
description: |
|
||||
This chapter goes over some advanced concepts of Fresh.
|
||||
---
|
||||
|
||||
This section of the documentation describes advanced functionality of Fresh.
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
description: "Create re-usable layouts across routes"
|
||||
---
|
||||
|
||||
Layouts are plain Preact components that are inherited based on the matching
|
||||
pattern. When you have a section on your site where all pages share the same
|
||||
HTML structure and only the content changes, a layout is a neat way to abstract
|
||||
this. Layouts only ever render on the server. The passed `Component` value
|
||||
represents the children of this component.
|
||||
|
||||
```tsx main.tsx
|
||||
function PageLayout({ Component }) {
|
||||
return (
|
||||
<div>
|
||||
<Component />
|
||||
<aside>Here is some sidebar content</aside>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const app = new App()
|
||||
.layout("*", PageLayout)
|
||||
.get("/", (ctx) => ctx.render(<h1>hello</h1>));
|
||||
```
|
||||
|
||||
If you browse to the `/` route, Fresh will render the following HTML
|
||||
|
||||
```html Response body
|
||||
<div>
|
||||
<h1>hello world</h1>
|
||||
<aside>Here is some sidebar content</aside>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
Add a layout and ignore all previously inherited ones.
|
||||
|
||||
```ts main.ts
|
||||
app.layout("/foo/bar", MyComponent, { skipInheritedLayouts: true });
|
||||
```
|
||||
|
||||
Ignore the app wrapper component:
|
||||
|
||||
```ts main.ts
|
||||
app.layout("/foo/bar", MyComponent, { skipAppWrapper: true });
|
||||
```
|
||||
@@ -0,0 +1,230 @@
|
||||
---
|
||||
description: |
|
||||
Partials allow areas of a page to be updated without causing the browser to reload the page. They enable optimized fine grained UI updates and can be used to do client-side navigation.
|
||||
---
|
||||
|
||||
Partials allow areas of the page to be updated with new content by the server
|
||||
without causing the browser to reload the page. They make your website feel more
|
||||
app-like because only the parts of the page that need to be updated will be
|
||||
updated.
|
||||
|
||||
## Enabling partials
|
||||
|
||||
Partials are enabled by adding a `f-client-nav` attribute to an HTML element and
|
||||
wrapping one or more areas in the page with a
|
||||
`<Partial name="my-partial">`-component.
|
||||
|
||||
The quickest way to get started is to enable partials for every page in
|
||||
`routes/_app.tsx` by making the following changes.
|
||||
|
||||
```diff routes/_app.tsx
|
||||
import { define } from "../utils.ts";
|
||||
+ import { Partial } from "fresh/runtime";
|
||||
|
||||
export default define.page(function App({ Component }) {
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>My Fresh app</title>
|
||||
</head>
|
||||
- <body>
|
||||
+ <body f-client-nav>
|
||||
+ <Partial name="body">
|
||||
<Component />
|
||||
+ </Partial>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
By adding the `f-client-nav` attribute, we enable partials for every element
|
||||
beneath the `<body>`-tag. To mark an area of the page as a partial we wrap it
|
||||
with a `<Partial>`-component with a unique name.
|
||||
|
||||
Behind the scenes, when the user clicks an `<a>`-tag, Fresh fetches the new page
|
||||
and only pulls out the relevant content out of the HTML response. When it finds
|
||||
a matching partial area it will update the content inside the partial.
|
||||
|
||||
> [info]: The `name` prop of the `<Partial>` component is expected to be unique
|
||||
> among Partials. That's how Fresh knows which parts of the response need to go
|
||||
> on the current page.
|
||||
|
||||
> [info]: Passing `f-client-nav={false}` disables client side navigation for all
|
||||
> elements below the current node.
|
||||
|
||||
### Optimizing partial requests
|
||||
|
||||
By default, with `f-client-nav` set, Fresh fetches the full next page and only
|
||||
picks out the relevant parts of the response. We can optimize this pattern
|
||||
further by only rendering the parts we need, instead of always rendering the
|
||||
full page. This is done by adding the `f-partial` attribute to a link.
|
||||
|
||||
```diff routes/_app.tsx
|
||||
- <a href="/docs/routes">Routes</a>
|
||||
+ <a href="/docs/routes" f-partial="/partials/docs/routes">Routes</a>
|
||||
```
|
||||
|
||||
When the `f-partial` attribute is present, Fresh will navigate to the page URL
|
||||
defined in the `href` attribute, but fetch the updated UI from the URL specified
|
||||
in `f-partial` instead. This can be a highly optimized route that only delivers
|
||||
the content you care about.
|
||||
|
||||
Let's use a typical documentation page layout as an example. It often features a
|
||||
main content area and a sidebar of links to switch between pages of the
|
||||
documentation (marked green here).
|
||||
|
||||

|
||||
|
||||
The code for such a page (excluding styling) might look like this:
|
||||
|
||||
```tsx routes/docs/[id].tsx
|
||||
import { define } from "../../utils.ts";
|
||||
|
||||
export default define.page(async (ctx) => {
|
||||
const content = await loadContent(ctx.params.id);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<aside>
|
||||
<a href="/docs/page1">Page 1</a>
|
||||
<a href="/docs/page2">Page 2</a>
|
||||
</aside>
|
||||
<Partial name="docs-content">
|
||||
{content}
|
||||
</Partial>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
An optimal route that only renders the content instead of the outer layout with
|
||||
the sidebar might look like this respectively.
|
||||
|
||||
```tsx routes/partials/docs/[id].tsx
|
||||
import { define } from "../utils.ts";
|
||||
import { Partial } from "fresh/runtime";
|
||||
|
||||
// We only want to render the content, so disable
|
||||
// the `_app.tsx` template as well as any potentially
|
||||
// inherited layouts
|
||||
export const config: RouteConfig = {
|
||||
skipAppWrapper: true,
|
||||
skipInheritedLayouts: true,
|
||||
};
|
||||
|
||||
export default define.page(async (ctx) => {
|
||||
const content = await loadContent(ctx.params.id);
|
||||
|
||||
// Only render the new content
|
||||
return (
|
||||
<Partial name="docs-content">
|
||||
{content}
|
||||
</Partial>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
By adding the `f-partial` attribute we tell Fresh to fetch the content from our
|
||||
newly added `/partials/docs/[id].tsx` route.
|
||||
|
||||
```diff routes/docs/[id].tsx
|
||||
<aside>
|
||||
- <a href="/docs/page1">Page 1</a>
|
||||
- <a href="/docs/page2">Page 2</a>
|
||||
+ <a href="/docs/page1" f-partial="/partials/docs/page1">Page 1</a>
|
||||
+ <a href="/docs/page2" f-partial="/partials/docs/page2">Page 2</a>
|
||||
</aside>
|
||||
```
|
||||
|
||||
With this in place, Fresh will navigate to the new page when clicking any of the
|
||||
two links and _only_ load the content rendered by our optimized partial route.
|
||||
|
||||
> Currently, `f-partial` is scoped to `<a>`, `<button>` and `<form>` elements.
|
||||
> This might be extended to more elements in the future.
|
||||
|
||||
## Sending multiple Partials at the same time
|
||||
|
||||
A neat aspect of partials in Fresh is that a response can return as many
|
||||
partials as desired. That way you can update multiple unrelated areas on your
|
||||
page in one single HTTP response. A scenario where this is useful are online
|
||||
shops for example.
|
||||
|
||||
```tsx routes/partials/cart.tsx
|
||||
export default function AddToCartPartial() {
|
||||
return (
|
||||
<>
|
||||
<Partial name="cart-items" mode="append">
|
||||
{/* Render the new cart item here */}
|
||||
</Partial>
|
||||
<Partial name="total-price">
|
||||
<p>Total: {totalPrice} €</p>
|
||||
</Partial>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Both partials will be applied to the current page.
|
||||
|
||||
## Replacement mode
|
||||
|
||||
By default the whole content inside a partial will be replaced, but there are
|
||||
scenarios where you want to prepend or append new content instead. This can be
|
||||
achieved by adding the `mode` prop to a `Partial` component.
|
||||
|
||||
- `replace` - Swap out the content of the existing partial (default)
|
||||
- `prepend` - Insert the new content before the existing content
|
||||
- `append` - Insert the new content after the existing content
|
||||
|
||||
Personally, we’ve found that the `append` mode is really useful when you have an
|
||||
UI which displays log messages or similar list-like data.
|
||||
|
||||
```tsx routes/log.tsx
|
||||
export default function LogView() {
|
||||
const lines = getNewLogLines();
|
||||
|
||||
return (
|
||||
<Partial name="logs-list" mode="append">
|
||||
{lines.map((line) => {
|
||||
return <li key={line}>{line}</li>;
|
||||
})}
|
||||
</Partial>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
> [info]: When picking the `prepend` or `append` mode, make sure to add keys to
|
||||
> the elements.
|
||||
|
||||
## Bypassing or disabling Partials
|
||||
|
||||
If you want to exempt a particular element from triggering a partial request
|
||||
like on a particular link, form or button, you can opt out of it by setting
|
||||
`f-client-nav={false}` on the element or one of the ancestor elements.
|
||||
|
||||
```tsx routes/_app.tsx
|
||||
<body f-client-nav>
|
||||
{/* This will cause a partial navigation */}
|
||||
<a href="/docs/page1">With partials</a>
|
||||
|
||||
{/* This WONT cause a partial navigation */}
|
||||
<a href="/docs/page1" f-client-nav={false}>No partials</a>
|
||||
|
||||
{/* This WONT cause a partial navigation on any elements below */}
|
||||
<div f-client-nav={false}>
|
||||
<div>
|
||||
<a href="/docs/page1">No partials</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>;
|
||||
```
|
||||
|
||||
Whenever an element is clicked Fresh checks if it has the `f-client-nav`
|
||||
attribute and if it is set to `true`. If the element itself doesn't have such an
|
||||
attribute, it will check if any of the ancestor elements has it. If an element
|
||||
was found with a truthy `f-client-nav` attribute a partial request will be
|
||||
triggered. If there is no such attribute or if it's set to `false`, no partial
|
||||
request will occur.
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
description: |
|
||||
Troubleshooting Fresh applications.
|
||||
---
|
||||
|
||||
This site contains some tips to troubleshoot your app in case something doesn't
|
||||
work as expected.
|
||||
|
||||
## Update Fresh
|
||||
|
||||
The easiest way to resolve most issues is to ensure that you're on the
|
||||
[latest version](https://jsr.io/@fresh/core/versions) of Fresh. We continuously
|
||||
work on Fresh and there is a good chance that the issue you're running into has
|
||||
already been resolved in the latest version of Fresh.
|
||||
|
||||
## Don't use esm.sh
|
||||
|
||||
Fresh 1.x heavily relied on [esm.sh](https://esm.sh/) to be able to use npm
|
||||
packages with Fresh. This continued a bit through the early alpha versions of
|
||||
Fresh 2. With the move to [`vite`](https://vite.dev/) this is not necessary
|
||||
anymore and you should use the relevant npm package directly from npm.
|
||||
|
||||
```diff deno.json
|
||||
{
|
||||
"imports": {
|
||||
- "cowsay": "https://esm.sh/cowsay"
|
||||
+ "cowsay": "npm:cowsay@^1.6.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> [info]: Not using `esm.sh` solves many issues and footguns with duplicate
|
||||
> Preact versions in your app. If you're seeing strange JavaScript errors in the
|
||||
> browser in your app than this is likely the cause.
|
||||
|
||||
## Attach a debugger
|
||||
|
||||
To attach a debugger to vite with Deno run this command:
|
||||
|
||||
```sh Terminal
|
||||
deno run -A --inspect npm:vite
|
||||
# or
|
||||
deno run -A --inspect-brk npm:vite
|
||||
```
|
||||
|
||||
## Debug vite resolution
|
||||
|
||||
To debug vite resolution issues run vite with the `--debug` flag. This will
|
||||
print lots of debugging information to the terminal.
|
||||
|
||||
## Debug vite transformations
|
||||
|
||||
To debug vite plugin transformations, use
|
||||
[`vite-plugin-inspect`](https://github.com/antfu-collective/vite-plugin-inspect).
|
||||
This gives you a UI that shows all transformations of all plugins for every
|
||||
file.
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
description: |
|
||||
Configure the fresh vite plugin.
|
||||
---
|
||||
|
||||
The Fresh vite plugin can be optionally configured in the following ways:
|
||||
|
||||
```ts vite.config.ts
|
||||
import { defineConfig, type Plugin } from "vite";
|
||||
import { fresh } from "@fresh/plugin-vite";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
fresh({
|
||||
// Path to main server entry file. Default: main.ts
|
||||
serverEntry: "./path/to/main.ts",
|
||||
// Path to main client entry file. Default: client.ts
|
||||
clientEntry: "./path/to/client.ts",
|
||||
// Path to islands directory. Default: ./islands
|
||||
islandsDir: "./islands",
|
||||
// Path to routes directory. Default: ./routes
|
||||
routeDir: "./routes",
|
||||
// Optional regex to ignore folders when crawling the routes and
|
||||
// island directory.
|
||||
ignore: [/[\\/]+some-folder[\\/]+/],
|
||||
// Additional specifiers to treat as island files. This is used
|
||||
// for declaring islands from third party packages.
|
||||
islandSpecifiers: ["@example/my-remote-island"],
|
||||
}),
|
||||
],
|
||||
});
|
||||
```
|
||||
Reference in New Issue
Block a user