docs: update for vite (#3308)

Update docs for vite
This commit is contained in:
Marvin Hagemeister
2025-09-02 10:45:27 +02:00
committed by GitHub
parent 6ddc0fbbcb
commit 9e58af7a5c
18 changed files with 372 additions and 318 deletions
+195
View File
@@ -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, {});
```
+13 -23
View File
@@ -20,9 +20,9 @@ This example demonstrates how to handle `application/x-www-form-urlencoded`
`<form>` submissions:
```tsx routes/subscribe.tsx
import { Handlers } from "$fresh/server.ts";
import { define } from "../utils.ts";
export const handler: Handlers = {
export const handlers = define.handlers({
async GET(req, ctx) {
return await ctx.render();
},
@@ -40,9 +40,9 @@ export const handler: Handlers = {
headers,
});
},
};
});
export default function Subscribe() {
export default define.page<typeof handlers>(function Subscribe() {
return (
<>
<form method="post">
@@ -51,7 +51,7 @@ export default function Subscribe() {
</form>
</>
);
}
});
```
When the user submits the form, Deno will retrieve the `email` value using the
@@ -65,26 +65,18 @@ that this time, we have to explicitly declare the form's encoding to be
`multipart/form-data`.
```tsx routes/subscribe.tsx
import { Handlers, type PageProps } from "$fresh/server.ts";
import { define } from "../utils.ts";
interface Props {
message: string | null;
}
export const handler: Handlers<Props> = {
export const handler = define.handlers({
async GET(req, ctx) {
return await ctx.render({
message: null,
});
return { data: { message: null } };
},
async POST(req, ctx) {
const form = await req.formData();
const file = form.get("my-file") as File;
if (!file) {
return ctx.render({
message: `Please try again`,
});
return { data: { message: "Please try again" } };
}
const name = file.name;
@@ -92,13 +84,11 @@ export const handler: Handlers<Props> = {
console.log(contents);
return ctx.render({
message: `${name} uploaded!`,
});
return { data: { message: `${name} uploaded!` } };
},
};
});
export default function Upload(props: PageProps<Props>) {
export default define.page<typeof handlers>(function Upload(props) {
const { message } = props.data;
return (
<>
@@ -109,7 +99,7 @@ export default function Upload(props: PageProps<Props>) {
{message ? <p>{message}</p> : null}
</>
);
}
});
```
## A note of caution
+6
View File
@@ -0,0 +1,6 @@
---
description: |
This chapter goes over some advanced concepts of Fresh.
---
This section of the documentation describes advanced functionality of Fresh.
+10 -8
View File
@@ -18,10 +18,10 @@ 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 { PageProps } from "$fresh/server.ts";
+ import { Partial } from "$fresh/runtime.ts";
import { define } from "../utils.ts";
+ import { Partial } from "fresh/runtime";
export default function App({ Component }: PageProps) {
export default define.page(function App({ Component }) {
return (
<html>
<head>
@@ -37,7 +37,7 @@ The quickest way to get started is to enable partials for every page in
</body>
</html>
);
}
});
```
By adding the `f-client-nav` attribute, we enable partials for every element
@@ -81,7 +81,9 @@ documentation (marked green here).
The code for such a page (excluding styling) might look like this:
```tsx routes/docs/[id].tsx
export default defineRoute(async (req, ctx) => {
import { define } from "../../utils.ts";
export default define.page(async (ctx) => {
const content = await loadContent(ctx.params.id);
return (
@@ -102,8 +104,8 @@ 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 { defineRoute, RouteConfig } from "$fresh/server.ts";
import { Partial } from "$fresh/runtime.ts";
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
@@ -113,7 +115,7 @@ export const config: RouteConfig = {
skipInheritedLayouts: true,
};
export default defineRoute(async (req, ctx) => {
export default define.page(async (ctx) => {
const content = await loadContent(ctx.params.id);
// Only render the new content
+32
View 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"],
}),
],
});
```