chore: release 1.4.0 (#1639)

This commit is contained in:
Marvin Hagemeister
2023-08-16 17:35:29 +02:00
committed by GitHub
parent 1e45dd4587
commit c175e28bf3
8 changed files with 101 additions and 319 deletions
@@ -1,135 +0,0 @@
---
description: |
Fresh optimize assets ahead of time, which makes pages load way quicker.
---
Fresh enables you to pre-optimize frontend assets before the code is deployed.
During that process the code for Islands will be compressed and optimized, so
that Fresh can send as little code as possible to the browser. Depending on the
amount of code an island needs, this process can take several seconds if done on
the fly serverside.
Doing those optimizations ahead-of-time and deploying the already optimized
assets alongside with your code, allows Fresh to treat them as like any other
static file and can serve it immediately without any further processing. On
pages with islands, having to do no processing greatly speeds up page load
times.
## Creating an optimized build
To have Fresh optimize all the assets, run one of the following commands:
```sh
# As a task in newer Fresh projects
deno task build
# or invoke it manually
deno run -A dev.ts build
```
This will create a `_fresh` folder in the project directory. That folder
contains the optimized assets and a `snapshot.json` file which includes some
metadata for Fresh.
> ℹ️ The `_fresh` folder should not be committed to the repository. Add an entry
> in the `.gitignore` file to ensure that it is not committed. Create that file
> at the root of your git repository if not present.
>
> ```gitignore .gitignore
> # Ignore fresh build directory
> _fresh/
> ```
## Running Fresh with optimized assets
When Fresh is started in non-development mode (usually via `main.ts`), Fresh
will automatically pick up optimized assets when a `_fresh` folder exists. If
found, Fresh will print the following message to the terminal:
```sh Terminal output
Using snapshot found at /path/to/project/_fresh
```
## Deploying an optimized Fresh project
To generate optimized assets whenever you push changes to the `main` branch of
your project, copy the following GitHub action and add it under
`.github/workflows/deploy.yml` in your project.
```yml .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main]
pull_request:
branches: main
jobs:
deploy:
name: Deploy
runs-on: ubuntu-latest
permissions:
id-token: write # Needed for auth with Deno Deploy
contents: read # Needed to clone the repository
steps:
- name: Clone repository
uses: actions/checkout@v3
- name: Install Deno
uses: denoland/setup-deno@v1
with:
deno-version: v1.x
- name: Build step
run: "deno task build" # 📝 Update the build command(s) if necessary
- name: Upload to Deno Deploy
uses: denoland/deployctl@v1
with:
project: "example-project" # 📝 Update the deploy project name if necessary
entrypoint: "./main.ts" # 📝 Update the entrypoint if necessary
```
> ℹ️ **Important:** The project name here must match the project name you've
> picked in Deno Deploy.
On the Deno Deploy side change the GitHub integration mode to GitHub Actions.
You need to unlink first, if you have an existing project that's linked with the
"Automatic" mode.
![Deno Deploy UI screenshot that shows the project dropdown and highlights the GitHub Action option](/docs/deno-deploy-gh-action.jpg)
Once this is set up you're ready for your next deployment. Whenever a new PR is
merged into the `main` branch on GitHub the deploy action will be executed and
deploy the optimized assets to Deno Deploy.
## Migrating existing projects with Plugins
If you're using Fresh plugins, extract them into a `fresh.config.ts` file, so
that both the `dev.ts` and `main.ts` script have access to them.
```ts fresh.config.ts
import { defineConfig } from "$fresh/server.ts";
import twindPlugin from "$fresh/plugins/twind.ts";
import twindConfig from "./twind.config.ts";
export default defineConfig({
plugins: [twindPlugin(twindConfig)],
});
```
```ts main.ts
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
import config from "./fresh.config.ts";
await start(manifest, config);
```
```ts dev.ts
import dev from "$fresh/dev.ts";
import config from "./fresh.config.ts";
await dev(import.meta.url, "./main.ts", config);
```
-104
View File
@@ -1,104 +0,0 @@
---
description: |
Add a global app wrapper to provide common meta tags or context for application routes.
---
An app wrapper is defined in an `_app.tsx` file in `routes/` folder and is
typically used to create the outer structure of an HTML document. 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 (
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Fresh app</title>
</head>
<body>
<Component />
</body>
</html>
);
}
```
## Async app wrapper
Similar to routes and layouts, the app wrapper can be made asynchronous. This
changes the function signature so that the first argument is the `Request`
instsance and the second one is the `AppContext`.
```tsx routes/_app.tsx
import { AppContext } from "$fresh/server.ts";
export default async function App(req: Request, ctx: AppContext) {
const data = await loadData();
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>
<h1>Hello {data.name}</h1>
<ctx.Component />
</body>
</html>
);
}
```
### Define helper
To make it quicker to type the async app wrapper, Fresh includes a `defineApp`
helper which already infers the correct types for you.
```tsx routes/_app.tsx
import { defineApp } from "$fresh/server.ts";
export default defineApp(async (req, ctx) => {
const data = await loadData();
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>
<h1>Hello {data.name}</h1>
<ctx.Component />
</body>
</html>
);
});
```
## Disabling the app wrapper
Rendering the app wrapper can be skipped on a route or layout basis. To do that,
set `skipAppWrapper: true` to the layout or route config.
```tsx routes/my-special-route.tsx
export const config: RouteConfig {
skipAppWrapper: true; // Skip the app wrapper during rendering
}
export default function Page() {
// ...
}
```
-124
View File
@@ -1,124 +0,0 @@
---
description: |
Add a layout to provide common meta tags, context for application sub routes, and common layout.
---
An layout is defined in a `_layout.tsx` file in any sub directory (at any level)
under the `routes/` folder. It must contain a default export that is a regular
Preact component. Only one such layout is allowed per sub directory.
```txt Project structure
└── routes
   ├── sub
   │ ├── page.tsx
   │   └── index.tss
├── other
│ ├── _layout.tsx # will be applied on top of `routes/_layout.tsx`
│ └── page.tsx
├── _layout.tsx # will be applied to all routes
└── _app.tsx
```
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/sub/_layout.tsx
import { LayoutProps } from "$fresh/server.ts";
export default function Layout({ Component, state }: LayoutProps) {
// do something with state here
return (
<div class="layout">
<Component />
</div>
);
}
```
## Async layouts
In case you need to fetch data asynchronously before rendering the layout, you
can use an async layout to do so.
```tsx routes/sub/_layout.tsx
import { LayoutProps } from "$fresh/server.ts";
export default async function Layout(req: Request, ctx: LayoutContext) {
// do something with state here
const data = await loadData();
return (
<div class="layout">
<p>{data.greeting}</p>
<ctx.Component />
</div>
);
}
```
### Define helper
To make it a little quicker to write async layouts, Fresh ships with a
`defineLayout` helper which automatically infers the correct types for the
function arguments.
```tsx
import { defineLayout } from "$fresh/server.ts";
export default defineLayout(async (req, ctx) => {
const data = await loadData();
return (
<div class="layout">
<p>{data.greeting}</p>
<ctx.Component />
</div>
);
});
```
## Opting out of layout inheritance
Sometimes you want to opt out of the layout inheritance mechanism for a
particular route. This can be done via route configuration. Picture a directory
structure like this:
```txt Project structure
└── routes
   ├── sub
   │ ├── _layout_.tsx
   │ ├── special.tsx # should not inherit layouts
   │   └── index.tss
└── _layout.tsx
```
To make `routes/sub/special.tsx` opt out of rendering layouts we can set
`skipInheritedLayouts: true`.
```tsx routes/sub/special.tsx
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
skipInheritedLayouts: true, // Skip already inherited layouts
};
export default function MyPage() {
return <p>Hello world</p>;
}
```
You can skip already inherited layouts inside a layout file:
```tsx routes/special/_layout.sx
import { LayoutConfig } from "$fresh/server.ts";
export const config: LayoutConfig = {
skipInheritedLayouts: true, // Skip already inherited layouts
};
export default function MyPage() {
return <p>Hello world</p>;
}
```
-197
View File
@@ -1,197 +0,0 @@
---
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). `ctx.state` is normally set by modifying its
properties, e.g. `ctx.state.loggedIn = true`, but you can also replace the
entire object like `ctx.state = { loggedIn = true }`.
```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:
```txt Project Structure
└── 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 routes/[tenant]/admin/_middleware.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 routes/_middleware.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:
```sh Terminal
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.