www: move latest docs into latest folder (#1522)
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
---
|
||||
description: |
|
||||
Add a global application wrapper to provide common meta tags or context for application routes.
|
||||
---
|
||||
|
||||
An application wrapper is defined in an `_app.tsx` file in `routes/` folder. It
|
||||
must contain a default export that is a regular Preact component. Only one such
|
||||
wrapper is allowed per application.
|
||||
|
||||
The component to be wrapped is received via props, in addition to a few other
|
||||
things. This allows for the introduction of a global container functioning as a
|
||||
template which can be conditioned based on state and params. Note that any state
|
||||
set by middleware is available via `props.state`.
|
||||
|
||||
```tsx
|
||||
// routes/_app.tsx
|
||||
|
||||
import { AppProps } from "$fresh/server.ts";
|
||||
|
||||
export default function App({ Component, state }: AppProps) {
|
||||
//do something with state here
|
||||
return (
|
||||
<div class="wrapper">
|
||||
<Component />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
description: |
|
||||
Fresh's architecture is designed to make it easy to build fast, scalable, and reliable applications.
|
||||
---
|
||||
|
||||
Fresh is designed to make it easy to build fast, scalable, and reliable
|
||||
applications. To do this, it makes opinionated decisions about how one should
|
||||
build web applications. These decisions are backed by strong empirical data
|
||||
gathered from experts in the field. Some examples of these principles are:
|
||||
|
||||
- Page load times should be reduced to a minimum.
|
||||
- The work performed on the client should be minimized.
|
||||
- Errors should have a small blast radius - stuff should gracefully degrade.
|
||||
|
||||
The single biggest architecture decision that Fresh makes is its usage of the
|
||||
[islands architecture][islands] pattern. This means that Fresh applications ship
|
||||
pure HTML to the client by default. Parts of a server-rendered page can then be
|
||||
independently re-hydrated with interactive widgets (islands). This means that
|
||||
the client is only responsible for rendering parts of the page that are
|
||||
interactive enough to warrant the extra effort. Any content that is purely
|
||||
static does not have related client-side JavaScript and is thus very
|
||||
lightweight.
|
||||
|
||||
<!-- TODO(lucacasonato): elaborate on request handling, form actions, etc. -->
|
||||
|
||||
[islands]: https://www.patterns.dev/posts/islands-architecture/
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
description: |
|
||||
Data fetching in Fresh happens inside of route handler functions. These can pass route data to the page via page props.
|
||||
---
|
||||
|
||||
Server side data fetching in Fresh is accomplished through asynchronous handler
|
||||
functions. These handler functions can call a `ctx.render()` function with the
|
||||
data to be rendered as an argument. This data can then be retrieved by the page
|
||||
component through the `data` property on the `props`.
|
||||
|
||||
Here is an example:
|
||||
|
||||
```tsx
|
||||
interface Project {
|
||||
name: string;
|
||||
stars: number;
|
||||
}
|
||||
|
||||
export const handler: Handlers<Project> = {
|
||||
async GET(_req, ctx) {
|
||||
const project = await db.projects.findOne({ id: ctx.params.id });
|
||||
if (!project) {
|
||||
return new Response("Project not found", { status: 404 });
|
||||
}
|
||||
return ctx.render(project);
|
||||
},
|
||||
};
|
||||
|
||||
export default function ProjectPage(props: PageProps<Project>) {
|
||||
return (
|
||||
<div>
|
||||
<h1>{props.data.name}</h1>
|
||||
<p>{props.data.stars} stars</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The type parameter on the `PageProps`, `Handlers`, `Handler`, and
|
||||
`HandlerContext` can be used to enforce a TypeScript type to use for the render
|
||||
data. Fresh enforces during type checking that the types in all of these fields
|
||||
are compatible within a single page.
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
description: |
|
||||
Fresh can be deployed to a variety of platforms easily.
|
||||
---
|
||||
|
||||
While Fresh is designed to be deployed to [Deno Deploy][deno-deploy], it can be
|
||||
deployed to any system or platform that can run a Deno based web server.
|
||||
|
||||
Here are instructions for specific providers / systems:
|
||||
|
||||
- [Deno Deploy](#deno-deploy)
|
||||
- [Docker](#docker)
|
||||
|
||||
## Deno Deploy
|
||||
|
||||
The recommended way to deploy Fresh is by using Deno Deploy. Deno Deploy
|
||||
provides a GitHub integration that can deploy your Fresh projects to its
|
||||
globally distributed edge network in seconds, automatically.
|
||||
|
||||
View [the getting started guide][deploy-to-production] for instructions on how
|
||||
to deploy Fresh to Deno Deploy.
|
||||
|
||||
## Docker
|
||||
|
||||
You can deploy Fresh to any platform that can run Docker containers. Docker is a
|
||||
tool to containerize projects and portably run them on any supported platform.
|
||||
|
||||
When packaging your Fresh app for Docker, it is important that you set the
|
||||
`DENO_DEPLOYMENT_ID` environment variable in your container. This variable needs
|
||||
to be set to an opaque string ID that represents the version of your application
|
||||
that is currently being run. This could be a Git commit hash, or a hash of all
|
||||
files in your project. It is critical for the function of Fresh that this ID
|
||||
changes when _any_ file in your project changes - if it doesn't, incorrect
|
||||
caching **will** cause your project to not function correctly.
|
||||
|
||||
Here is an example `Dockerfile` for a Fresh project:
|
||||
|
||||
```dockerfile
|
||||
FROM denoland/deno:1.35.0
|
||||
|
||||
ARG GIT_REVISION
|
||||
ENV DENO_DEPLOYMENT_ID=${GIT_REVISION}
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
RUN deno cache main.ts
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["run", "-A", "main.ts"]
|
||||
```
|
||||
|
||||
To build your Docker image inside of a Git repository:
|
||||
|
||||
```sh
|
||||
$ docker build --build-arg GIT_REVISION=$(git rev-parse HEAD) -t my-fresh-app .
|
||||
```
|
||||
|
||||
Then run your Docker container:
|
||||
|
||||
```sh
|
||||
$ docker run -t -i -p 80:8000 my-fresh-app
|
||||
```
|
||||
|
||||
To deploy to a cloud provider, push it to a container registry and follow their
|
||||
documentation.
|
||||
|
||||
- [Amazon Web Services][aws-container-registry]
|
||||
- [Google Cloud][gcp-container-registry]
|
||||
|
||||
[aws-container-registry]: https://docs.aws.amazon.com/AmazonECS/latest/userguide/create-container-image.html#create-container-image-push-ecr
|
||||
[gcp-container-registry]: https://cloud.google.com/container-registry/docs/pushing-and-pulling
|
||||
[deno-deploy]: https://deno.com/deploy
|
||||
[deploy-to-production]: /docs/getting-started/deploy-to-production
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
description: |
|
||||
Error pages can be used to customize the page that is shown when an error occurs in the application.
|
||||
---
|
||||
|
||||
Fresh supports customizing the `404 Not Found`, and the
|
||||
`500 Internal Server Error` pages. These are shown when a request is made but no
|
||||
matching route exists, and when a middleware, route handler, or page component
|
||||
throws an error respectively.
|
||||
|
||||
### 404: Not Found
|
||||
|
||||
The 404 page can be customized by creating a `_404.tsx` file in the `routes/`
|
||||
folder. The file must have a default export that is a regular Preact component.
|
||||
A props object of type `UnknownPageProps` is passed in as an argument.
|
||||
|
||||
```tsx
|
||||
import { UnknownPageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function NotFoundPage({ url }: UnknownPageProps) {
|
||||
return <p>404 not found: {url.pathname}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
#### Manually render 404 pages
|
||||
|
||||
The `_404.tsx` file will be invoked automatically when no route matches the URL.
|
||||
In some cases, one needs to manually trigger the rendering of the 404 page, for
|
||||
example when the route did match, but the requested resource does not exist.
|
||||
This can be achieved with `ctx.renderNotFound`.
|
||||
|
||||
```tsx
|
||||
import { Handlers, PageProps } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(req, ctx) {
|
||||
const blogpost = await fetchBlogpost(ctx.params.slug);
|
||||
if (!blogpost) {
|
||||
return ctx.renderNotFound({
|
||||
custom: "prop",
|
||||
});
|
||||
}
|
||||
return ctx.render({ blogpost });
|
||||
},
|
||||
};
|
||||
|
||||
export default function BlogpostPage({ data }) {
|
||||
return (
|
||||
<article>
|
||||
<h1>{data.blogpost.title}</h1>
|
||||
{/* rest of your page */}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 500: Internal Server Error
|
||||
|
||||
The 500 page can be customized by creating a `_500.tsx` file in the `routes/`
|
||||
folder. The file must have a default export that is a regular Preact component.
|
||||
A props object of type `ErrorPageProps` is passed in as an argument.
|
||||
|
||||
```tsx
|
||||
import { ErrorPageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function Error500Page({ error }: ErrorPageProps) {
|
||||
return <p>500 internal error: {(error as Error).message}</p>;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
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 `multipart/form-data`
|
||||
|
||||
Forms can either submit as a `GET` request with URL search parameter encoding,
|
||||
or as a `POST` request with `multipart/form-data`.
|
||||
|
||||
This example demonstrates how to handle `multipart/form-data` `<form>`
|
||||
submissions:
|
||||
|
||||
```tsx
|
||||
// routes/subscribe.tsx
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(req, ctx) {
|
||||
return await ctx.render();
|
||||
},
|
||||
async POST(req, ctx) {
|
||||
const form = await 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 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 access a specific `email` value from a
|
||||
`formData()`, add the email to a list, and redirect the user to a thank you
|
||||
page.
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
description: |
|
||||
This chapter goes over some fundamental concepts of Fresh.
|
||||
---
|
||||
|
||||
This chapter goes over some fundamental concepts of Fresh. It covers the
|
||||
overarching architecture design of Fresh applications, as well as reference
|
||||
documentation about the various features of Fresh.
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
description: |
|
||||
Islands enable client side interactivity in Fresh. They are hydrated on the client in addition to being rendered on the server.
|
||||
---
|
||||
|
||||
Islands enable client side interactivity in Fresh. Islands are isolated Preact
|
||||
components that are rendered on the client. This is different from all other
|
||||
components in Fresh, as they are usually just rendered on the server.
|
||||
|
||||
Islands are defined by creating a file in the `islands/` folder in a Fresh
|
||||
project. The name of this file must be a PascalCase or kebab-case name of the
|
||||
island.
|
||||
|
||||
```tsx
|
||||
// islands/MyIsland.tsx
|
||||
|
||||
import { useSignal } from "@preact/signals";
|
||||
|
||||
export default function MyIsland() {
|
||||
const count = useSignal(0);
|
||||
|
||||
return (
|
||||
<div>
|
||||
Counter is at {count}.{" "}
|
||||
<button onClick={() => (count.value += 1)}>+</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
An island can be used in a page like a regular Preact component. Fresh will take
|
||||
care of automatically re-hydrating the island on the client.
|
||||
|
||||
Passing props to islands is supported, but only if the props are serializable.
|
||||
Fresh can serialize the following types of values:
|
||||
|
||||
- Primitive types `string`, `boolean`, `bigint`, and `null`
|
||||
- Most `number`s (`Infinity`, `-Infinity`, and `NaN` are silently converted to
|
||||
`null`)
|
||||
- Plain objects with string keys and serializable values
|
||||
- Arrays containing serializable values
|
||||
- Uint8Array
|
||||
- JSX Elements (restricted to `props.children`)
|
||||
- Preact Signals (if the inner value is serializable)
|
||||
|
||||
Circular references are supported. If an object or signal is referenced multiple
|
||||
times, it is only serialized once and the references are restored upon
|
||||
deserialization. Passing complex objects like `Date`, custom classes, or
|
||||
functions is not supported.
|
||||
|
||||
## Passing JSX to islands
|
||||
|
||||
Islands support passing JSX elements via the `children` property. This allows
|
||||
you to pass static content rendered by the server to an island in the browser.
|
||||
|
||||
```jsx
|
||||
// route/index.tsx
|
||||
import MyIsland from "../islands/my-island.tsx";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<MyIsland>
|
||||
<p>This text is rendered on the server</p>
|
||||
</MyIsland>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
We can deduce which parts were rendered by the server and which parts where
|
||||
rendered by an island from the HTML alone. It contains all the information we
|
||||
need, which allows us to skip the work of having to send a serialized version of
|
||||
`props.children` to the browser.
|
||||
|
||||
### Nesting islands
|
||||
|
||||
Islands can be nested within other islands as well. In that scenario they act
|
||||
like a normal Preact component, but still receive the serialized props if any
|
||||
were present.
|
||||
|
||||
```jsx
|
||||
// route/index.tsx
|
||||
import MyIsland from "../islands/my-island.tsx";
|
||||
import OtherIsland from "../islands/other-island.tsx";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<MyIsland>
|
||||
<OtherIsland foo="this prop will be serialized">
|
||||
<p>This text is rendered on the server</p>
|
||||
</OtherIsland>
|
||||
</MyIsland>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
In essence, Fresh allows you to mix static and interactive parts in your app in
|
||||
a way that's most optimal for your use app. We'll keep sending only the
|
||||
JavaScript that is needed for the islands to the browser.
|
||||
|
||||
```jsx
|
||||
// route/index.tsx
|
||||
import MyIsland from "../islands/my-island.tsx";
|
||||
import OtherIsland from "../islands/other-island.tsx";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<MyIsland>
|
||||
<div>
|
||||
<h1>Rendered by server</h1>
|
||||
<OtherIsland>
|
||||
<p>also rendered by server</p>
|
||||
</OtherIsland>
|
||||
</div>
|
||||
</MyIsland>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,199 @@
|
||||
---
|
||||
description: |
|
||||
Add middleware routes to intercept requests or responses for analytics purposes, access control, or anything else.
|
||||
---
|
||||
|
||||
A middleware is defined in a `_middleware.ts` file. It will intercept the
|
||||
request in order for you to perform custom logic before or after the route
|
||||
handler. This allows modifying or checking requests and responses. Common
|
||||
use-cases for this are logging, authentication, and performance monitoring.
|
||||
|
||||
Each middleware gets passed a `next` function in the context argument that is
|
||||
used to trigger child handlers. The `ctx` also has a `state` property that can
|
||||
be used to pass arbitrary data to downstream (or upstream) handlers. This
|
||||
`state` is included in `PageProps` by default, which is available to both the
|
||||
special [\_app](/docs/concepts/app-wrapper.md) wrapper and normal
|
||||
[routes](/docs/concepts/routes.md).
|
||||
|
||||
```ts
|
||||
// routes/_middleware.ts
|
||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||
|
||||
interface State {
|
||||
data: string;
|
||||
}
|
||||
|
||||
export async function handler(
|
||||
req: Request,
|
||||
ctx: MiddlewareHandlerContext<State>,
|
||||
) {
|
||||
ctx.state.data = "myData";
|
||||
const resp = await ctx.next();
|
||||
resp.headers.set("server", "fresh server");
|
||||
return resp;
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// routes/myHandler.ts
|
||||
export const handler: Handlers<any, { data: string }> = {
|
||||
GET(_req, ctx) {
|
||||
return new Response(`middleware data is ${ctx.state.data}`);
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
Middlewares are scoped and can be layered. This means a project can have
|
||||
multiple middlewares, each covering a different set of routes. If multiple
|
||||
middlewares cover a route, they will all be run, in order of specificity (least
|
||||
specific first).
|
||||
|
||||
For example, take a project with the following routes:
|
||||
|
||||
```
|
||||
└── routes
|
||||
├── _middleware.ts
|
||||
├── index.ts
|
||||
└── admin
|
||||
├── _middleware.ts
|
||||
└── index.ts
|
||||
└── signin.ts
|
||||
```
|
||||
|
||||
For a request to `/` the request will flow like this:
|
||||
|
||||
1. The `routes/_middleware.ts` middleware is invoked.
|
||||
2. Calling `ctx.next()` will invoke the `routes/index.ts` handler.
|
||||
|
||||
For a request to `/admin` the request flows like this:
|
||||
|
||||
1. The `routes/_middleware.ts` middleware is invoked.
|
||||
2. Calling `ctx.next()` will invoke the `routes/admin/_middleware.ts`
|
||||
middleware.
|
||||
3. Calling `ctx.next()` will invoke the `routes/admin/index.ts` handler.
|
||||
|
||||
For a request to `/admin/signin` the request flows like this:
|
||||
|
||||
1. The `routes/_middleware.ts` middleware is invoked.
|
||||
2. Calling `ctx.next()` will invoke the `routes/admin/_middleware.ts`
|
||||
middleware.
|
||||
3. Calling `ctx.next()` will invoke the `routes/admin/signin.ts` handler.
|
||||
|
||||
A single middleware file can also define multiple middlewares (all for the same
|
||||
route) by exporting an array of handlers instead of a single handler. For
|
||||
example:
|
||||
|
||||
```ts
|
||||
// routes/_middleware.ts
|
||||
|
||||
export const handler = [
|
||||
async function middleware1(req, ctx) {
|
||||
// do something
|
||||
return ctx.next();
|
||||
},
|
||||
async function middleware2(req, ctx) {
|
||||
// do something
|
||||
return ctx.next();
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
It should be noted that `middleware` has access to route parameters. If you're
|
||||
running a fictitious `routes/[tenant]/admin/_middleware.ts` like this:
|
||||
|
||||
```ts
|
||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||
|
||||
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
||||
const currentTenant = ctx.params.tenant;
|
||||
//do something with the tenant
|
||||
const resp = await ctx.next();
|
||||
return resp;
|
||||
}
|
||||
```
|
||||
|
||||
and the request is to `mysaas.com/acme/admin/`, then `currentTenant` will have
|
||||
the value of `acme` in your middleware.
|
||||
|
||||
## Middleware Destination
|
||||
|
||||
To set the stage for this section, `MiddlewareHandlerContext` looks like this:
|
||||
|
||||
```ts
|
||||
export interface MiddlewareHandlerContext<State = Record<string, unknown>> {
|
||||
next: () => Promise<Response>;
|
||||
state: State;
|
||||
destination: router.DestinationKind;
|
||||
remoteAddr: {
|
||||
transport: "tcp" | "udp";
|
||||
hostname: string;
|
||||
port: number;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
and `router.DestinationKind` is defined like this:
|
||||
|
||||
```ts
|
||||
export type DestinationKind = "internal" | "static" | "route" | "notFound";
|
||||
```
|
||||
|
||||
This is useful if you want your middleware to only run when a request is headed
|
||||
for a `route`, as opposed to something like `http://localhost:8001/favicon.ico`.
|
||||
|
||||
### Example
|
||||
|
||||
Initiate a new Fresh project (`deno run -A -r https://fresh.deno.dev/`) and then
|
||||
create a `_middleware.ts` file in the `routes` folder like this:
|
||||
|
||||
```ts
|
||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||
|
||||
export async function handler(req: Request, ctx: MiddlewareHandlerContext) {
|
||||
console.log(ctx.destination);
|
||||
console.log(req.url);
|
||||
const resp = await ctx.next();
|
||||
return resp;
|
||||
}
|
||||
```
|
||||
|
||||
If you start up your server (`deno task start`) you'll see the following:
|
||||
|
||||
```
|
||||
Task start deno run -A --watch=static/,routes/ dev.ts
|
||||
Watcher Process started.
|
||||
The manifest has been generated for 4 routes and 1 islands.
|
||||
|
||||
🍋 Fresh ready
|
||||
Local: http://localhost:8000/
|
||||
|
||||
route
|
||||
http://localhost:8000/
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/deserializer.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/signals.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/plugin-twind-main.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/main.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/island-counter.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/refresh.js
|
||||
static
|
||||
http://localhost:8000/logo.svg?__frsh_c=3c7400558fc00915df88cb181036c0dbf73ab7f5
|
||||
internal
|
||||
http://localhost:8000/_frsh/alive
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-PDMKJVJ5.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-UGFDDSOV.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-RCK7U3UF.js
|
||||
```
|
||||
|
||||
That first `route` request is for when `Fresh` responds with the root level
|
||||
`index.tsx` route. The rest, as you can see, are either `internal` or `static`
|
||||
requests. You can use `ctx.destination` to filter these out if your middleware
|
||||
is only supposed to deal with routes.
|
||||
@@ -0,0 +1,142 @@
|
||||
---
|
||||
description: Plugins can add new functionality to Fresh without requiring significant complexity.
|
||||
---
|
||||
|
||||
Plugins can dynamically add new functionality to Fresh without exposing
|
||||
significant complexity to the user. Users can add plugins by importing and
|
||||
initializing them in their `main.ts` file:
|
||||
|
||||
```ts
|
||||
// main.ts
|
||||
|
||||
import { start } from "$fresh/server.ts";
|
||||
import manifest from "./fresh.gen.ts";
|
||||
|
||||
import twindPlugin from "$fresh/plugins/twind.ts";
|
||||
import twindConfig from "./twind.config.js";
|
||||
|
||||
await start(manifest, {
|
||||
plugins: [
|
||||
// This line configures Fresh to use the first-party twind plugin.
|
||||
twindPlugin(twindConfig),
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Currently, the only available first-party plugin is the Twind plugin.
|
||||
Third-party plugins are also supported - they can be imported from any HTTP
|
||||
server, like any other Deno module.
|
||||
|
||||
Plugin hooks are executed in the order that the plugins are defined in the
|
||||
`plugins` array. This means that the first plugin in the array will be executed
|
||||
first, and the last plugin in the array will be executed last. For many plugins,
|
||||
this does not matter, but for some plugins it may.
|
||||
|
||||
## Creating a plugin
|
||||
|
||||
Fresh plugins are in essence a collection of hooks that allow the plugin to hook
|
||||
into various systems inside of Fresh. Currently only a `render` hook is
|
||||
available (explained below).
|
||||
|
||||
A Fresh plugin is just a JavaScript object that conforms to the
|
||||
[Plugin](https://deno.land/x/fresh/server.ts?s=Plugin) interface. The only
|
||||
required property of a plugin is its name. Names must only contain the
|
||||
characters `a`-`z`, and `_`.
|
||||
|
||||
```ts
|
||||
import { Plugin } from "$fresh/server.ts";
|
||||
|
||||
const plugin: Plugin = {
|
||||
name: "my_plugin",
|
||||
};
|
||||
```
|
||||
|
||||
A plugin containing only a name is technically valid, but not very useful. To be
|
||||
able to do anything with a plugin, it must register some hooks, middlewares, or
|
||||
routes.
|
||||
|
||||
### Hook: `render`
|
||||
|
||||
The render hook allows plugins to:
|
||||
|
||||
- Control timing of the synchronous render of a page.
|
||||
- Inject additional CSS and JS into the rendered page.
|
||||
|
||||
This is commonly used to set thread local variables for the duration of the
|
||||
render (for example preact global context, preact option hooks, or for style
|
||||
libraries like Twind). After render is complete, the plugin can inject inline
|
||||
CSS and JS modules (with attached state) into the page.
|
||||
|
||||
The render hook is called with the
|
||||
[`PluginRenderContext`](https://deno.land/x/fresh/server.ts?s=PluginRenderContext)
|
||||
object, which contains a `render()` method. This method must be invoked during
|
||||
the render hook to actually render the page. It is a terminal error to not call
|
||||
the `render()` method during the render hook.
|
||||
|
||||
The `render()` method returns a
|
||||
[`PluginRenderFunctionResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderFunctionResult)
|
||||
object which contains the HTML text of the rendered page, as well as a boolean
|
||||
indicating whether the page contains any islands that will be hydrated on the
|
||||
client.
|
||||
|
||||
The `render` hook needs to synchronously return a
|
||||
[`PluginRenderResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderResult)
|
||||
object. Additional CSS and JS modules can be added to be injected into the page
|
||||
by adding them to `styles` and `scripts` arrays in this object.
|
||||
|
||||
`styles` are injected into the `<head>` of the page as inline CSS. Each entry
|
||||
can define the CSS text to inject, as well as an optional `id` for the style
|
||||
tag, and an optional `media` attribute for the style tag.
|
||||
|
||||
`scripts` define JavaScript/TypeScript modules to be injected into the page. The
|
||||
possibly loaded modules need to be defined up front in the `Plugin#entrypoints`
|
||||
property. Each defined module must be a JavaScript/TypeScript module that has a
|
||||
default export of a function that takes one (arbitrary) argument, and returns
|
||||
nothing (or a promise resolving to nothing). Fresh will call this function with
|
||||
the state defined in the `scripts` entry. The state can be any arbitrary JSON
|
||||
serializable JavaScript value.
|
||||
|
||||
For an example of a plugin that uses the `render` hook, see the first-party
|
||||
[Twind plugin](https://github.com/denoland/fresh/blob/main/plugins/twind.ts).
|
||||
|
||||
### Hook: `renderAsync`
|
||||
|
||||
This hook is largely the same as the `render` hook, with a couple of key
|
||||
differences to make asynchronous style and script generation possible. It must
|
||||
asynchronously return its
|
||||
[`PluginRenderResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderResult),
|
||||
either from an `async/await` function or wrapped within a promise.
|
||||
|
||||
The render hook is called with the
|
||||
[`PluginAsyncRenderContext`](https://deno.land/x/fresh/server.ts?s=PluginAsyncRenderContext)
|
||||
object, which contains a `renderAsync()` method. This method must be invoked
|
||||
during the render hook to actually render the page. It is a terminal error to
|
||||
not call the `renderAsync()` method during the render hook.
|
||||
|
||||
This is useful for when plugins are generating styles and scripts with
|
||||
asynchronous dependencies based on the `htmlText`. Unlike the synchronous render
|
||||
hook, async render hooks for multiple pages can be running at the same time.
|
||||
This means that unlike the synchronous render hook, you can not use global
|
||||
variables to propagate state between the render hook and the renderer.
|
||||
|
||||
The `renderAsync` hooks start before any page rendering occurs, and finish after
|
||||
all rendering is complete -- they wrap around the underlying JSX->string
|
||||
rendering, plugin `render` hooks, and the
|
||||
[`RenderFunction`](https://deno.land/x/fresh/server.ts?s=RenderFunction) that
|
||||
may be provided to Fresh's `start` entrypoint in the `main.ts` file.
|
||||
|
||||
### Routes and Middlewares
|
||||
|
||||
You can create routes and middlewares that get loaded and rendered like the
|
||||
normal [routes](/docs/concepts/routes) and
|
||||
[middlewares](/docs/concepts/middleware).
|
||||
|
||||
The plugin routes and middlewares need a defined path in the format of a file
|
||||
name without a filetype inside the routes directory(E.g. `blog/index`,
|
||||
`blog/[slug]`).
|
||||
|
||||
For more examples see the [Concepts: Routing](/docs/concepts/routing) page.
|
||||
|
||||
To create a middleware you need to create a `MiddlewareHandler` function.
|
||||
|
||||
And to create a route you can create both a Handler and/or component.
|
||||
@@ -0,0 +1,173 @@
|
||||
---
|
||||
description: |
|
||||
Routes are the basic building block of Fresh applications. They are used to define the behaviour the application when a given path is requested.
|
||||
---
|
||||
|
||||
At their core, routes describe how a request for a given path should be handled,
|
||||
and what the response should be. To do this, routes have two main parts: the
|
||||
handler, and the component. A route can have either one, or both, but never
|
||||
neither.
|
||||
|
||||
The handler is a function that is called for every request to the route. It
|
||||
needs to return a response that is then sent to the client. The response could
|
||||
be anything: a plain text string, a JSON object, an HTML page, a WebSocket
|
||||
connection, a streaming file, or pretty much anything else. The handler is
|
||||
passed a `render` function that it can call to invoke rendering a component.
|
||||
|
||||
The component is the template for a page. It is a JSX element that is rendered
|
||||
on the server. The page component gets passed props that can be used by it to
|
||||
determine exactly what should be rendered. By default components receives props
|
||||
consisting of: the request URL, the matching route (as a string), the matches
|
||||
from the URL pattern match, any state set by middleware, and any data passed to
|
||||
the handler's `render` function.
|
||||
|
||||
## Handler route
|
||||
|
||||
Let's look at a basic route that returns a plain text string:
|
||||
|
||||
```tsx
|
||||
// routes/plain.tsx
|
||||
|
||||
import { HandlerContext, Handlers } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
GET(_req: Request, _ctx: HandlerContext) {
|
||||
return new Response("Hello World");
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
To define a handler, one needs to export a `handler` function or object from the
|
||||
route module. If the handler is an object, each key in the object is the name of
|
||||
the HTTP method that the handler should be called for. For example the `GET`
|
||||
handler above is called for `GET` requests. If the handler is a function, it is
|
||||
called for all requests regardless of the method. If an HTTP method does not
|
||||
have a corresponding handler, a 405 HTTP error is returned.
|
||||
|
||||
## Component route
|
||||
|
||||
Now, let's render some HTML using the route component:
|
||||
|
||||
```tsx
|
||||
// routes/html.tsx
|
||||
|
||||
import { PageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function Page(props: PageProps) {
|
||||
return <div>You are on the page '{props.url.href}'.</div>;
|
||||
}
|
||||
```
|
||||
|
||||
The page component needs to be the default export of the route module. It is
|
||||
passed props that can be used to render the page.
|
||||
|
||||
As you can see in the second example, if no handler is explicitly defined a
|
||||
default handler is used that just renders out the page component if present. You
|
||||
can also override the default handler though to modify how exactly rendering
|
||||
should work.
|
||||
|
||||
## Mixed handler and component route
|
||||
|
||||
In the below example, a custom handler is used to add a custom header to the
|
||||
response after rendering the page component.
|
||||
|
||||
```tsx
|
||||
// routes/html.tsx
|
||||
|
||||
import { HandlerContext, Handlers, PageProps } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(_req: Request, ctx: HandlerContext) {
|
||||
const resp = await ctx.render();
|
||||
resp.headers.set("X-Custom-Header", "Hello World");
|
||||
return resp;
|
||||
},
|
||||
};
|
||||
|
||||
export default function Page(props: PageProps) {
|
||||
return <div>You are on the page '{props.url.href}'.</div>;
|
||||
}
|
||||
```
|
||||
|
||||
## Async route components
|
||||
|
||||
Having a separate route handler and component function is nice, when you want to
|
||||
test these in isolation, but can become a bit cumbersome to maintain. They
|
||||
require some additional indirection of declaring an interface for the component
|
||||
`Data` when you're passing it around through `ctx.render()`.
|
||||
|
||||
```tsx
|
||||
interface Data {
|
||||
foo: number;
|
||||
}
|
||||
|
||||
export const handler: Handlers<Data> = {
|
||||
async GET(req, ctx) {
|
||||
const value = await loadFooValue();
|
||||
ctx.render({ foo: value });
|
||||
},
|
||||
};
|
||||
|
||||
export default function MyPage(props: PageProps<Data>) {
|
||||
return <p>foo is: {props.data.foo}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
When a route has both a component and a `GET` handler, they are typically very
|
||||
closely coupled. With async route components you can merge the two together and
|
||||
avoid having to create the `Data` interface boilerplate.
|
||||
|
||||
```tsx
|
||||
// Async route component
|
||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||
const value = await loadFooValue();
|
||||
return <p>foo is: {value}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
The code gets a little shorter with async route components. Conceptually, you
|
||||
can think of async route components inlining the `GET` handler into the
|
||||
component function. Note, that you can still add additional HTTP handlers in the
|
||||
same file like before.
|
||||
|
||||
```tsx
|
||||
export const handler: Handlers = {
|
||||
async POST(req) {
|
||||
// ... do something here
|
||||
},
|
||||
};
|
||||
|
||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||
const value = await loadFooValue();
|
||||
return <p>foo is: {value}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
### Returning Response objects
|
||||
|
||||
Quite often a route handler needs to render a 404 page or bail out of rendering
|
||||
in another manner. This can be done by returning a `Response` object.
|
||||
|
||||
```tsx
|
||||
// Async route component
|
||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||
const value = await loadFooValue();
|
||||
|
||||
// Return 404 if `value` is null
|
||||
if (value === null) {
|
||||
return ctx.renderNotFound();
|
||||
}
|
||||
|
||||
// Returning a response object directly works too
|
||||
if (value === "redirect") {
|
||||
const headers = new Headers();
|
||||
headers.set("location", "/some-other-page");
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
return <p>foo is: {value}</p>;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
description: |
|
||||
File based routing is the simplest way to do routing in Fresh apps. Additionally custom patterns can be configured per route.
|
||||
---
|
||||
|
||||
Routing is the mechanism that determines what route a given incoming request is
|
||||
handled by. Fresh routes requests based on their URL path. By default routes
|
||||
specify which paths they are invoked for using the name of the file. Routes can
|
||||
also define a custom [URL pattern][urlpattern] to match against for more
|
||||
advanced use cases.
|
||||
|
||||
The file based routing in Fresh is very similar to the file based routing seen
|
||||
in other frameworks, namely Next.js. File names are used to determine which
|
||||
route a given request should be handled by. The pattern is determined based on
|
||||
the path of the file on disk, relative to the `routes/` directory.
|
||||
|
||||
File names are mapped to route patterns as follows:
|
||||
|
||||
- File extensions are ignored.
|
||||
- Literals in the file path are treated as string literals to match.
|
||||
- Files named `<path>/index.<ext>` behave identically to a file named
|
||||
`<path>.<ext>`.
|
||||
- Path segments can be made dynamic by surrounding an identifier with `[` and
|
||||
`]`.
|
||||
- Paths where the last path segment follows the structure `[...<ident>]` are
|
||||
treated as having a wildcard suffix.
|
||||
|
||||
Here is a table of file names, which route patterns they map to, and which paths
|
||||
they might match:
|
||||
|
||||
| File name | Route pattern | Matching paths |
|
||||
| ------------------------- | ---------------------- | -------------------------- |
|
||||
| `index.ts` | `/` | `/` |
|
||||
| `about.ts` | `/about` | `/about` |
|
||||
| `blog/index.ts` | `/blog` | `/blog` |
|
||||
| `blog/[slug].ts` | `/blog/:slug` | `/blog/foo`, `/blog/bar` |
|
||||
| `blog/[slug]/comments.ts` | `/blog/:slug/comments` | `/blog/foo/comments` |
|
||||
| `old/[...path].ts` | `/old/:path*` | `/old/foo`, `/old/bar/baz` |
|
||||
|
||||
Advanced use-cases can require that a more complex pattern be used for matching.
|
||||
A custom [URL pattern][urlpattern] can be specified in the route configuration.
|
||||
This pattern will be used instead of the file path based pattern:
|
||||
|
||||
```ts
|
||||
// routes/x.ts
|
||||
|
||||
import { RouteConfig } from "$fresh/server.ts";
|
||||
|
||||
export const config: RouteConfig = {
|
||||
routeOverride: "/x/:module@:version/:path*",
|
||||
};
|
||||
|
||||
// ...
|
||||
```
|
||||
|
||||
[urlpattern]: https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
description: |
|
||||
Fresh's architecture is designed to leverage server components by default.
|
||||
---
|
||||
|
||||
If you've read about Fresh's [architecture](/docs/concepts/architecture) then
|
||||
you know that it's based on the islands architecture pattern. The flip side of
|
||||
this is that everything else is, by default, a server component. When you
|
||||
[create a route](/docs/getting-started/create-a-route), all of the components
|
||||
used are rendered on the server. No javascript is sent to the client, unless you
|
||||
specifically include something from the `/islands/` folder.
|
||||
|
||||
Internally, Fresh's rendering heavily leverages
|
||||
[preact-render-to-string](https://github.com/preactjs/preact-render-to-string).
|
||||
This is the exact library mentioned on Preact's
|
||||
[Server-Side Rendering](https://preactjs.com/guide/v10/server-side-rendering/)
|
||||
article.
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
description: |
|
||||
The ability to configure the core Fresh server leads to its flexibility.
|
||||
---
|
||||
|
||||
In this page we discuss how the server can be configured during startup.
|
||||
|
||||
The signature of the primary method looks like this:
|
||||
|
||||
```ts
|
||||
export async function start(routes: Manifest, opts: StartOptions = {});
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
`Manifest` comes from `fresh.gen.ts`, so nothing to do there. `opts` is where
|
||||
things get interesting. `StartOptions` looks like this:
|
||||
|
||||
```
|
||||
export type StartOptions = ServeInit & FreshOptions;
|
||||
```
|
||||
|
||||
The good stuff is really in...
|
||||
|
||||
```ts
|
||||
export interface FreshOptions {
|
||||
render?: RenderFunction;
|
||||
plugins?: Plugin[];
|
||||
staticDir?: string;
|
||||
router?: RouterOptions;
|
||||
}
|
||||
```
|
||||
|
||||
And for brevity here are the remaining two types:
|
||||
|
||||
```ts
|
||||
export type RenderFunction = (
|
||||
ctx: RenderContext,
|
||||
render: InnerRenderFunction,
|
||||
) => void | Promise<void>;
|
||||
|
||||
export interface RouterOptions {
|
||||
/**
|
||||
* @default {false}
|
||||
*/
|
||||
trailingSlash?: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
## Plugins
|
||||
|
||||
See the [docs](/docs/concepts/plugins) on this topic for more detail. But for
|
||||
completion, you can do something like this to load plugins:
|
||||
|
||||
```ts
|
||||
await start(manifest, { plugins: [twindPlugin(twindConfig)] });
|
||||
```
|
||||
|
||||
## StaticDir
|
||||
|
||||
This allows you to specify the location where your site's static assets are
|
||||
stored. Here's an example:
|
||||
|
||||
```ts
|
||||
await start(manifest, { staticDir: "./custom_static" });
|
||||
```
|
||||
|
||||
## Render
|
||||
|
||||
This is by far the most complicated option currently available. It allows you to
|
||||
configure how your components get rendered.
|
||||
|
||||
A detailed, concrete example of this is changing the language of the `<html>`
|
||||
tag. See the documentation [here](/docs/examples/setting-the-language).
|
||||
|
||||
## RouterOptions
|
||||
|
||||
### TrailingSlash
|
||||
|
||||
By default Fresh uses URLs like `https://www.example.com/about`. If you'd like,
|
||||
you can configure this to `https://www.example.com/about/` by using the
|
||||
`trailingSlash` setting.
|
||||
|
||||
```ts
|
||||
await start(manifest, { router: { trailingSlash: true } });
|
||||
```
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
description: |
|
||||
Fresh has built-in support for serving static files. This is useful for serving images, CSS, and other static assets.
|
||||
---
|
||||
|
||||
Fresh automatically serves static assets placed in a `static/` directory in the
|
||||
project root. These assets are served at the root of the webserver, with a
|
||||
higher priority than routes. This means that if a given request matches a file
|
||||
in the `static/` folder, it is always served, even if there is a route that
|
||||
would also match the request.
|
||||
|
||||
Static asset responses automatically get a `content-type` header assigned based
|
||||
on the file extension of the file on disk. Assets are also automatically
|
||||
streamed from disk to the client to improve performance and efficiency for both
|
||||
user and server.
|
||||
|
||||
Fresh also adds an `etag` header to assets automatically and handles the
|
||||
`If-None-Match` header for incoming requests.
|
||||
|
||||
### Caching
|
||||
|
||||
By default, no caching headers are added to assets. This can be disadvantageous
|
||||
in many scenarios, so Fresh makes it easy to serve assets with long cache
|
||||
lifetimes too.
|
||||
|
||||
The first approach to do this is manual. The client runtime exports an `asset`
|
||||
function that takes an absolute path to the static asset and returns a "locked"
|
||||
version of this path that contains a build ID for cache busting. When the asset
|
||||
is requested at this "locked" path, it will be served with a cache lifetime of
|
||||
one year.
|
||||
|
||||
```jsx
|
||||
import { asset } from "$fresh/runtime.ts";
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<p>
|
||||
<a href={asset("/brochure.pdf")}>View brochure</a>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Fresh also does this automatically for `src` and `srcset` attributes in `<img>`
|
||||
and `<source>` HTML tags. These will automatically use "locked" paths if Fresh
|
||||
deems it safe to do so. You can always opt out of this behaviour per tag, by
|
||||
adding the `data-fresh-disable-lock` attribute.
|
||||
|
||||
```jsx
|
||||
<img src="/user.png" />;
|
||||
```
|
||||
@@ -0,0 +1,128 @@
|
||||
---
|
||||
description: |
|
||||
New versions of Fresh are regularly released. This page explains how to update your project.
|
||||
---
|
||||
|
||||
Fresh constists of multiple pieces which are independently versioned and
|
||||
released.
|
||||
|
||||
- Fresh (https://deno.land/x/fresh)
|
||||
- Preact (https://esm.sh/preact)
|
||||
- preact-render-to-string (https://esm.sh/preact-render-to-string)
|
||||
|
||||
Some plugins also have their own dependencies that can be updated independently.
|
||||
|
||||
- Twind (https://esm.sh/twind) (for the twind plugin)
|
||||
|
||||
For the most part these pieces can be updated independently. Certain versions of
|
||||
Fresh may require a minimum version of a given dependency. This is documented
|
||||
below.
|
||||
|
||||
| Fresh version | Preact | preact-render-to-string | Deno |
|
||||
| ------------- | ----------------- | ----------------------- | --------- |
|
||||
| 1.0.0-1.0.2 | >=10.8.1 <11.0.0 | >=5.2.0 <6.0.0 | >= 1.23.0 |
|
||||
| 1.1.0-1.1.5 | >=10.8.1 <11.0.0 | >=5.2.0 <6.0.0 | >= 1.25.0 |
|
||||
| 1.2.0 | >=10.15.0 <11.0.0 | >=6.1.0 | >= 1.25.0 |
|
||||
|
||||
## Updating dependencies
|
||||
|
||||
To update your dependencies, you have two options:
|
||||
|
||||
- Run the Fresh updater to update your project dependencies.
|
||||
- Manually update the dependency versions in your `deno.json` file.
|
||||
|
||||
### Auto updater
|
||||
|
||||
The auto updater is a command line tool that will update your project's
|
||||
`deno.json` file to the latest versions of Fresh and its dependencies. It may
|
||||
also contain code mods for your project that will update your code to the latest
|
||||
recommended patterns for Fresh projects.
|
||||
|
||||
To run the auto updater, run the following command from the root of your
|
||||
project:
|
||||
|
||||
```bash
|
||||
$ deno run -A -r https://fresh.deno.dev/update .
|
||||
```
|
||||
|
||||
You will be prompted to confirm the changes that will be made to your project.
|
||||
|
||||
### Manual update
|
||||
|
||||
To manually update your project's dependencies, you can edit the `deno.json`
|
||||
file in the root of your projects directory. Dependency versions are encoded
|
||||
into the URLs in this file. For example, here is how to update a project from
|
||||
Fresh 1.0.2 to 1.1.3, and update Preact to the latest version:
|
||||
|
||||
```diff
|
||||
{
|
||||
"imports": {
|
||||
- "$fresh/": "https://deno.land/x/fresh@1.0.2/",
|
||||
+ "$fresh/": "https://deno.land/x/fresh@1.1.5/",
|
||||
|
||||
- "preact": "https://esm.sh/preact@10.8.1",
|
||||
- "preact/": "https://esm.sh/preact@10.8.1/",
|
||||
+ "preact": "https://esm.sh/preact@10.11.0",
|
||||
+ "preact/": "https://esm.sh/preact@10.11.0/",
|
||||
|
||||
- "preact-render-to-string": "https://esm.sh/*preact-render-to-string@5.2.0",
|
||||
+ "preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.1.0",
|
||||
|
||||
"twind": "https://esm.sh/twind@0.16.17",
|
||||
"twind/": "https://esm.sh/twind@0.16.17/"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Automatic update checks
|
||||
|
||||
Fresh will periodically check if a new Fresh version is available if it's
|
||||
running outside of CI. This happens once per day and can be disabled by setting
|
||||
the `FRESH_NO_UPDATE_CHECK=true` environment variable.
|
||||
|
||||
## Code mods
|
||||
|
||||
Code mods are small scripts that can be run to update your project's code to
|
||||
match the latest recommended patterns for Fresh projects. Code mods can be run
|
||||
through the auto updater. Sometimes the code mod can not cover all cases, so you
|
||||
may need to manually update some code. This section explains the code mods
|
||||
currently available.
|
||||
|
||||
### Classical JSX -> Automatic JSX
|
||||
|
||||
> This code mod is only available in Fresh 1.1.0 and above.
|
||||
|
||||
The classical JSX transform that relies on a `/** @jsx h */` pragma is no longer
|
||||
the recommended way to use JSX in Fresh projects. Instead, starting with version
|
||||
1.1.0, Fresh projects should use the automatic JSX transform that requires no
|
||||
JSX pragma or preact import.
|
||||
|
||||
```diff
|
||||
- /** @jsx h */
|
||||
- import { h } from "preact";
|
||||
|
||||
export default function Page() {
|
||||
return <div>Hello world!</div>;
|
||||
}
|
||||
```
|
||||
|
||||
This code mod will update your deno.json file to include the relevant compiler
|
||||
options to enable the automatic JSX transform. It will then go through your
|
||||
project and remove any `/** @jsx h */` pragmas and `import { h } from "preact"`
|
||||
statements.
|
||||
|
||||
### Classic twind -> Twind plugin
|
||||
|
||||
> This code mod is only available in Fresh 1.1.0 and above.
|
||||
|
||||
Fresh version 1.1.0 introduced a new plugin for using twind with Fresh. This
|
||||
plugin is much nicer to use than the raw twind integration that was previously
|
||||
available.
|
||||
|
||||
This code mod will update your project to use the new twind plugin. It will
|
||||
update your `main.ts` file to import the twind plugin and add it to the plugins
|
||||
array. It will also update your files to remove many unnecessary uses of the
|
||||
`tw` function, and remove unnecessary twind imports. While the code mod can
|
||||
handle most cases, you may need to manually update some code. Additionally you
|
||||
will need to manually update your `twind.config.ts` if you use a custom
|
||||
configuration.
|
||||
Reference in New Issue
Block a user