@@ -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, {});
|
||||||
|
```
|
||||||
@@ -20,9 +20,9 @@ This example demonstrates how to handle `application/x-www-form-urlencoded`
|
|||||||
`<form>` submissions:
|
`<form>` submissions:
|
||||||
|
|
||||||
```tsx routes/subscribe.tsx
|
```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) {
|
async GET(req, ctx) {
|
||||||
return await ctx.render();
|
return await ctx.render();
|
||||||
},
|
},
|
||||||
@@ -40,9 +40,9 @@ export const handler: Handlers = {
|
|||||||
headers,
|
headers,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
};
|
});
|
||||||
|
|
||||||
export default function Subscribe() {
|
export default define.page<typeof handlers>(function Subscribe() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<form method="post">
|
<form method="post">
|
||||||
@@ -51,7 +51,7 @@ export default function Subscribe() {
|
|||||||
</form>
|
</form>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
When the user submits the form, Deno will retrieve the `email` value using the
|
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`.
|
`multipart/form-data`.
|
||||||
|
|
||||||
```tsx routes/subscribe.tsx
|
```tsx routes/subscribe.tsx
|
||||||
import { Handlers, type PageProps } from "$fresh/server.ts";
|
import { define } from "../utils.ts";
|
||||||
|
|
||||||
interface Props {
|
export const handler = define.handlers({
|
||||||
message: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const handler: Handlers<Props> = {
|
|
||||||
async GET(req, ctx) {
|
async GET(req, ctx) {
|
||||||
return await ctx.render({
|
return { data: { message: null } };
|
||||||
message: null,
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
async POST(req, ctx) {
|
async POST(req, ctx) {
|
||||||
const form = await req.formData();
|
const form = await req.formData();
|
||||||
const file = form.get("my-file") as File;
|
const file = form.get("my-file") as File;
|
||||||
|
|
||||||
if (!file) {
|
if (!file) {
|
||||||
return ctx.render({
|
return { data: { message: "Please try again" } };
|
||||||
message: `Please try again`,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const name = file.name;
|
const name = file.name;
|
||||||
@@ -92,13 +84,11 @@ export const handler: Handlers<Props> = {
|
|||||||
|
|
||||||
console.log(contents);
|
console.log(contents);
|
||||||
|
|
||||||
return ctx.render({
|
return { data: { message: `${name} uploaded!` } };
|
||||||
message: `${name} uploaded!`,
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
};
|
});
|
||||||
|
|
||||||
export default function Upload(props: PageProps<Props>) {
|
export default define.page<typeof handlers>(function Upload(props) {
|
||||||
const { message } = props.data;
|
const { message } = props.data;
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -109,7 +99,7 @@ export default function Upload(props: PageProps<Props>) {
|
|||||||
{message ? <p>{message}</p> : null}
|
{message ? <p>{message}</p> : null}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
## A note of caution
|
## A note of caution
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
---
|
||||||
|
description: |
|
||||||
|
This chapter goes over some advanced concepts of Fresh.
|
||||||
|
---
|
||||||
|
|
||||||
|
This section of the documentation describes advanced functionality of Fresh.
|
||||||
@@ -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.
|
`routes/_app.tsx` by making the following changes.
|
||||||
|
|
||||||
```diff routes/_app.tsx
|
```diff routes/_app.tsx
|
||||||
import { PageProps } from "$fresh/server.ts";
|
import { define } from "../utils.ts";
|
||||||
+ import { Partial } from "$fresh/runtime.ts";
|
+ import { Partial } from "fresh/runtime";
|
||||||
|
|
||||||
export default function App({ Component }: PageProps) {
|
export default define.page(function App({ Component }) {
|
||||||
return (
|
return (
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
@@ -37,7 +37,7 @@ The quickest way to get started is to enable partials for every page in
|
|||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
}
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
By adding the `f-client-nav` attribute, we enable partials for every element
|
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:
|
The code for such a page (excluding styling) might look like this:
|
||||||
|
|
||||||
```tsx routes/docs/[id].tsx
|
```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);
|
const content = await loadContent(ctx.params.id);
|
||||||
|
|
||||||
return (
|
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.
|
the sidebar might look like this respectively.
|
||||||
|
|
||||||
```tsx routes/partials/docs/[id].tsx
|
```tsx routes/partials/docs/[id].tsx
|
||||||
import { defineRoute, RouteConfig } from "$fresh/server.ts";
|
import { define } from "../utils.ts";
|
||||||
import { Partial } from "$fresh/runtime.ts";
|
import { Partial } from "fresh/runtime";
|
||||||
|
|
||||||
// We only want to render the content, so disable
|
// We only want to render the content, so disable
|
||||||
// the `_app.tsx` template as well as any potentially
|
// the `_app.tsx` template as well as any potentially
|
||||||
@@ -113,7 +115,7 @@ export const config: RouteConfig = {
|
|||||||
skipInheritedLayouts: true,
|
skipInheritedLayouts: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default defineRoute(async (req, ctx) => {
|
export default define.page(async (ctx) => {
|
||||||
const content = await loadContent(ctx.params.id);
|
const content = await loadContent(ctx.params.id);
|
||||||
|
|
||||||
// Only render the new content
|
// Only render the new content
|
||||||
|
|||||||
@@ -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"],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
```
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
---
|
|
||||||
description: |
|
|
||||||
The Builder class is used to generate optimized assets for production.
|
|
||||||
---
|
|
||||||
|
|
||||||
The `Builder` class in Fresh is where you'll do everything related to builds.
|
|
||||||
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.
|
|
||||||
@@ -6,21 +6,9 @@ description: |
|
|||||||
Use the `.fsRoutes()` helper on the [`App`](/docs/canary/concepts/app) instance
|
Use the `.fsRoutes()` helper on the [`App`](/docs/canary/concepts/app) instance
|
||||||
to specify where file based routes should be inserted. It adds routes based on
|
to specify where file based routes should be inserted. It adds routes based on
|
||||||
the structure in the `routes/` folder in your project (or any other folder you
|
the structure in the `routes/` folder in your project (or any other folder you
|
||||||
have set in `dev.ts`). When you add a new file there, it will register a new
|
have specified when instantiating the
|
||||||
route automatically.
|
[`fresh()` vite plugin](/docs/canary/advanced/vite). in `vite.config.ts`). When
|
||||||
|
you add a new file there, it will register a new route automatically.
|
||||||
```ts main.ts
|
|
||||||
import { Builder } from "fresh/dev";
|
|
||||||
|
|
||||||
// Optionally set a custom route dir (will be `<root>/routes` by default)
|
|
||||||
const builder = new Builder({ routeDir: "path/to/routes" });
|
|
||||||
|
|
||||||
if (Deno.args.includes("build")) {
|
|
||||||
await builder.build();
|
|
||||||
} else {
|
|
||||||
await builder.listen(() => import("./main.ts"));
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```ts main.ts
|
```ts main.ts
|
||||||
import { App, staticFiles } from "fresh";
|
import { App, staticFiles } from "fresh";
|
||||||
@@ -40,7 +28,7 @@ Example project structure:
|
|||||||
<project root>
|
<project root>
|
||||||
├── deno.json
|
├── deno.json
|
||||||
├── main.ts
|
├── main.ts
|
||||||
├── dev.ts
|
├── vite.config.ts
|
||||||
└── routes
|
└── routes
|
||||||
├── (marketing) # Route group, used to group related routes
|
├── (marketing) # Route group, used to group related routes
|
||||||
│ ├── _layout.tsx # Apply layout to all routes in this directory
|
│ ├── _layout.tsx # Apply layout to all routes in this directory
|
||||||
|
|||||||
@@ -29,9 +29,11 @@ An island can be used anywhere like a regular Preact component. Fresh will take
|
|||||||
care of making it interactive on the client.
|
care of making it interactive on the client.
|
||||||
|
|
||||||
```tsx main.tsx
|
```tsx main.tsx
|
||||||
|
import { App, staticFiles } from "fresh";
|
||||||
import MyIsland from "./islands/my-island.tsx";
|
import MyIsland from "./islands/my-island.tsx";
|
||||||
|
|
||||||
const app = new App()
|
const app = new App()
|
||||||
|
.use(staticFiles())
|
||||||
.get("/", (ctx) => ctx.render(<MyIsland />));
|
.get("/", (ctx) => ctx.render(<MyIsland />));
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -72,9 +74,11 @@ A powerful feature of Fresh is that you can pass server-rendered JSX to an
|
|||||||
island via props.
|
island via props.
|
||||||
|
|
||||||
```tsx routes/index.tsx
|
```tsx routes/index.tsx
|
||||||
|
import { staticFiles } from "fresh";
|
||||||
import MyIsland from "../islands/my-island.tsx";
|
import MyIsland from "../islands/my-island.tsx";
|
||||||
|
|
||||||
const app = new App()
|
const app = new App()
|
||||||
|
.use(staticFiles())
|
||||||
.get("/", (ctx) => {
|
.get("/", (ctx) => {
|
||||||
return ctx.render(
|
return ctx.render(
|
||||||
<MyIsland jsx={<h1>hello</h1>}>
|
<MyIsland jsx={<h1>hello</h1>}>
|
||||||
|
|||||||
@@ -26,16 +26,16 @@ template which can be conditioned based on state and params. Note that any state
|
|||||||
set by middleware is available via `props.state`.
|
set by middleware is available via `props.state`.
|
||||||
|
|
||||||
```tsx routes/sub/_layout.tsx
|
```tsx routes/sub/_layout.tsx
|
||||||
import { PageProps } from "$fresh/server.ts";
|
import { define } from "../../utils.ts";
|
||||||
|
|
||||||
export default function Layout({ Component, state }: PageProps) {
|
export default define.layout({ Component, state }) => {
|
||||||
// do something with state here
|
// do something with state here
|
||||||
return (
|
return (
|
||||||
<div class="layout">
|
<div class="layout">
|
||||||
<Component />
|
<Component />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
## Async layouts
|
## Async layouts
|
||||||
@@ -44,33 +44,12 @@ In case you need to fetch data asynchronously before rendering the layout, you
|
|||||||
can use an async layout to do so.
|
can use an async layout to do so.
|
||||||
|
|
||||||
```tsx routes/sub/_layout.tsx
|
```tsx routes/sub/_layout.tsx
|
||||||
import { FreshContext } from "$fresh/server.ts";
|
import { define } from "../../utils.ts";
|
||||||
|
|
||||||
export default async function Layout(req: Request, ctx: FreshContext) {
|
export default define.layout(async (ctx) => {
|
||||||
// do something with state here
|
// do something with state here
|
||||||
const data = await loadData();
|
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 (
|
return (
|
||||||
<div class="layout">
|
<div class="layout">
|
||||||
<p>{data.greeting}</p>
|
<p>{data.greeting}</p>
|
||||||
@@ -99,21 +78,22 @@ To make `routes/sub/special.tsx` opt out of rendering layouts we can set
|
|||||||
`skipInheritedLayouts: true`.
|
`skipInheritedLayouts: true`.
|
||||||
|
|
||||||
```tsx routes/sub/special.tsx
|
```tsx routes/sub/special.tsx
|
||||||
import { RouteConfig } from "$fresh/server.ts";
|
import { type RouteConfig } from "fresh";
|
||||||
|
import { define } from "../../utils.ts";
|
||||||
|
|
||||||
export const config: RouteConfig = {
|
export const config: RouteConfig = {
|
||||||
skipInheritedLayouts: true, // Skip already inherited layouts
|
skipInheritedLayouts: true, // Skip already inherited layouts
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function MyPage() {
|
export default define.layout(() => {
|
||||||
return <p>Hello world</p>;
|
return <p>Hello world</p>;
|
||||||
}
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
You can skip already inherited layouts inside a layout file:
|
You can skip already inherited layouts inside a layout file:
|
||||||
|
|
||||||
```tsx routes/special/_layout.tsx
|
```tsx routes/special/_layout.tsx
|
||||||
import { LayoutConfig } from "$fresh/server.ts";
|
import { type LayoutConfig } from "fresh";
|
||||||
|
|
||||||
export const config: LayoutConfig = {
|
export const config: LayoutConfig = {
|
||||||
skipInheritedLayouts: true, // Skip already inherited layouts
|
skipInheritedLayouts: true, // Skip already inherited layouts
|
||||||
|
|||||||
@@ -16,15 +16,6 @@ const app = new App()
|
|||||||
.use(staticFiles());
|
.use(staticFiles());
|
||||||
```
|
```
|
||||||
|
|
||||||
The path to the static file directory can be customized on the
|
|
||||||
[`Builder` class](/docs/canary/concepts/builder) inside your `dev.ts` file.
|
|
||||||
|
|
||||||
```ts dev.ts
|
|
||||||
import { Builder } from "fresh/dev";
|
|
||||||
|
|
||||||
const builder = new Builder({ staticDir: "path/to/staticDir" });
|
|
||||||
```
|
|
||||||
|
|
||||||
## Caching headers
|
## Caching headers
|
||||||
|
|
||||||
By default, Fresh adds caching headers for the `src` and `srcset` attributes on
|
By default, Fresh adds caching headers for the `src` and `srcset` attributes on
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
---
|
||||||
|
description: "Deploy Fresh on Cloudflare Workers"
|
||||||
|
---
|
||||||
|
|
||||||
|
Deploy Fresh to Cloudflare Workers by following these instructions:
|
||||||
|
|
||||||
|
1. Run `deno install --allow-scripts npm:@cloudflare/vite-plugin npm:wrangler`
|
||||||
|
2. Add the cloudflare plugin in your vite configuration file:
|
||||||
|
|
||||||
|
```diff vite.config.ts
|
||||||
|
import { defineConfig } from "vite";
|
||||||
|
import { fresh } from "@fresh/plugin-vite";
|
||||||
|
+ import { cloudflare } from "@cloudflare/vite-plugin";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [
|
||||||
|
fresh(),
|
||||||
|
+ cloudflare(),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Follow further instructions provided by the cloudflare vite plugin.
|
||||||
|
|
||||||
|
Check out the
|
||||||
|
[Cloudflare Documentation](https://developers.cloudflare.com/workers/vite-plugin/)
|
||||||
|
for further information.
|
||||||
@@ -32,7 +32,7 @@ anymore either.
|
|||||||
```diff Project structure
|
```diff Project structure
|
||||||
<project root>
|
<project root>
|
||||||
├── routes/
|
├── routes/
|
||||||
├── dev.ts
|
- ├── dev.ts
|
||||||
- ├── fresh.gen.ts
|
- ├── fresh.gen.ts
|
||||||
- ├── fresh.config.ts
|
- ├── fresh.config.ts
|
||||||
└── main.ts
|
└── main.ts
|
||||||
@@ -43,36 +43,42 @@ development is separate from production code. This split makes deployments much
|
|||||||
smaller, quicker to upload and allows them to boot up much quicker in
|
smaller, quicker to upload and allows them to boot up much quicker in
|
||||||
production.
|
production.
|
||||||
|
|
||||||
### Updating `dev.ts`
|
### Replacing `dev.ts` with `vite.config.ts`
|
||||||
|
|
||||||
Development related configuration can be passed to the `Builder` class instance
|
Delete `dev.ts` and create a `vite.config.ts` file instead. Pass your custom
|
||||||
in `dev.ts`. This file is also where you typically set up development-only
|
Fresh configuration to the [fresh vite plugin](/docs/canary/advanced/vite).
|
||||||
plugins like [tailwindcss](https://tailwindcss.com/).
|
|
||||||
|
|
||||||
The full `dev.ts` file for newly generated Fresh 2 projects looks like this:
|
```ts vite.config.ts
|
||||||
|
import { defineConfig } from "vite";
|
||||||
|
import { fresh } from "@fresh/plugin-vite";
|
||||||
|
import tailwindcss from "@tailwindcss/vite";
|
||||||
|
|
||||||
```ts dev.ts
|
export default defineConfig({
|
||||||
import { Builder } from "fresh/dev";
|
plugins: [
|
||||||
import { tailwind } from "@fresh/plugin-tailwind";
|
fresh(),
|
||||||
|
tailwindcss(),
|
||||||
// Pass development only configuration here
|
],
|
||||||
const builder = new Builder({ target: "safari12" });
|
});
|
||||||
|
|
||||||
// Example: Enabling the tailwind plugin for Fresh
|
|
||||||
tailwind(builder);
|
|
||||||
|
|
||||||
// Create optimized assets for the browser when
|
|
||||||
// running `deno run -A dev.ts build`
|
|
||||||
if (Deno.args.includes("build")) {
|
|
||||||
await builder.build();
|
|
||||||
} else {
|
|
||||||
// ...otherwise start the development server
|
|
||||||
await builder.listen(() => import("./main.ts"));
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
> [info]: Fresh 1.x used Tailwind CSS v3. To keep using v3 use the
|
### Add a `client.ts` file
|
||||||
> `@fresh/plugin-tailwind-v3` instead.
|
|
||||||
|
The `client.ts` file is the main entry file for client-side code. Since vite
|
||||||
|
requires everything to be part of the internal module graph to get hot module
|
||||||
|
reloading to work, this is also the place where you import CSS assets.
|
||||||
|
|
||||||
|
```diff Project structure
|
||||||
|
<project root>
|
||||||
|
├── routes/
|
||||||
|
+ ├── client.ts
|
||||||
|
├── vite.config.ts
|
||||||
|
└── main.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
```ts client.ts
|
||||||
|
// Import CSS files here for hot module reloading to work.
|
||||||
|
import "./assets/styles.css";
|
||||||
|
```
|
||||||
|
|
||||||
### Updating `main.ts`
|
### Updating `main.ts`
|
||||||
|
|
||||||
@@ -139,9 +145,11 @@ accordingly.
|
|||||||
```diff deno.json
|
```diff deno.json
|
||||||
{
|
{
|
||||||
"tasks":
|
"tasks":
|
||||||
"dev": "deno run -A dev.ts",
|
- "dev": "deno run -A dev.ts",
|
||||||
"build": "deno run -A dev.ts build",
|
- "build": "deno run -A dev.ts build",
|
||||||
- "preview": "deno run -A main.ts"
|
- "preview": "deno run -A main.ts"
|
||||||
|
+ "dev": "vite",
|
||||||
|
+ "build": "vite build",
|
||||||
+ "preview": "deno serve -A _fresh/server.js"
|
+ "preview": "deno serve -A _fresh/server.js"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -229,33 +237,8 @@ re-use existing objects internally as a minor performance optimization.
|
|||||||
## `createHandler`
|
## `createHandler`
|
||||||
|
|
||||||
The `createHandler` function was often used to launch Fresh for tests. This can
|
The `createHandler` function was often used to launch Fresh for tests. This can
|
||||||
be now done via the [`Builder`](/docs/canary/concepts/builder).
|
be now done via vite's `createBuilder` function. See the
|
||||||
|
[testing page](/docs/canary/testing) for more information.
|
||||||
```ts main.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"));
|
|
||||||
// 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");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
## Getting help
|
## Getting help
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ project folder should look like this:
|
|||||||
|
|
||||||
```txt-files Project structure
|
```txt-files Project structure
|
||||||
<project root>
|
<project root>
|
||||||
|
├── components/ # Store other components here. Can be named differently
|
||||||
|
│ └── Button.tsx
|
||||||
├── islands/ # Components that need JS to run client-side
|
├── islands/ # Components that need JS to run client-side
|
||||||
│ └── Counter.tsx
|
│ └── Counter.tsx
|
||||||
├── routes/ # File system based routes
|
├── routes/ # File system based routes
|
||||||
@@ -27,10 +29,11 @@ project folder should look like this:
|
|||||||
│ └── index.tsx # Renders /
|
│ └── index.tsx # Renders /
|
||||||
├── static/ # Contains static assets like css, logos, etc
|
├── static/ # Contains static assets like css, logos, etc
|
||||||
│ └── ...
|
│ └── ...
|
||||||
│
|
│
|
||||||
├── deno.json # Contains dependencies, tasks, etc
|
├── client.ts # Client entry file that's loaded on every page.
|
||||||
├── dev.ts # Run this during development
|
├── main.ts # The server entry file of your app
|
||||||
└── main.ts # Run this for production
|
├── deno.json # Contains dependencies, tasks, etc
|
||||||
|
└── vite.config.ts # Vite configuration file
|
||||||
```
|
```
|
||||||
|
|
||||||
Run the `dev` task to launch your app in development mode:
|
Run the `dev` task to launch your app in development mode:
|
||||||
|
|||||||
@@ -1,66 +0,0 @@
|
|||||||
---
|
|
||||||
description: "Use Tailwindcss to style your app"
|
|
||||||
---
|
|
||||||
|
|
||||||
[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, {});
|
|
||||||
```
|
|
||||||
@@ -112,23 +112,21 @@ Deno.test("MyLayout - renders heading and content", async () => {
|
|||||||
many app instances in our test suite.
|
many app instances in our test suite.
|
||||||
|
|
||||||
```ts my-app.test.ts
|
```ts my-app.test.ts
|
||||||
|
import { createBuilder } from "vite";
|
||||||
// Best to do this once instead of for every test case for
|
// Best to do this once instead of for every test case for
|
||||||
// performance reasons.
|
// performance reasons.
|
||||||
const builder = new Builder();
|
const builder = await createBuilder({
|
||||||
const applySnapshot = await builder.build({ snapshot: "memory" });
|
root: "./path/to/app",
|
||||||
|
build: {
|
||||||
|
emptyOutDir: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await builder.build();
|
||||||
|
|
||||||
function testApp() {
|
const { app } = await import("./path/to/app/_fresh/server.js");
|
||||||
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 () => {
|
Deno.test("My Test", async () => {
|
||||||
const handler = testApp().handler();
|
const handler = app.handler();
|
||||||
|
|
||||||
const response = await handler(new Request("http://localhost"));
|
const response = await handler(new Request("http://localhost"));
|
||||||
const text = await response.text();
|
const text = await response.text();
|
||||||
|
|||||||
+3
-2
@@ -39,7 +39,6 @@ const toc: RawTableOfContents = {
|
|||||||
["islands", "Islands", "link:canary"],
|
["islands", "Islands", "link:canary"],
|
||||||
["static-files", "Static files", "link:canary"],
|
["static-files", "Static files", "link:canary"],
|
||||||
|
|
||||||
["builder", "Builder", "link:canary"],
|
|
||||||
["file-routing", "File routing", "link:canary"],
|
["file-routing", "File routing", "link:canary"],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -55,6 +54,8 @@ const toc: RawTableOfContents = {
|
|||||||
["define", "Define Helpers", "link:canary"],
|
["define", "Define Helpers", "link:canary"],
|
||||||
["environment-variables", "Environment Variables", "link:canary"],
|
["environment-variables", "Environment Variables", "link:canary"],
|
||||||
["head", "Modifying <head>", "link:canary"],
|
["head", "Modifying <head>", "link:canary"],
|
||||||
|
["vite", "Vite Plugin Options", "link:canary"],
|
||||||
|
["builder", "Builder (Legacy)", "link:canary"],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
deployment: {
|
deployment: {
|
||||||
@@ -64,6 +65,7 @@ const toc: RawTableOfContents = {
|
|||||||
["deno-deploy", "Deno Deploy", "link:canary"],
|
["deno-deploy", "Deno Deploy", "link:canary"],
|
||||||
["deno-compile", "deno compile", "link:canary"],
|
["deno-compile", "deno compile", "link:canary"],
|
||||||
["docker", "Docker", "link:canary"],
|
["docker", "Docker", "link:canary"],
|
||||||
|
["cloudflare-workers", "Cloudflare Workers", "link:canary"],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
testing: {
|
testing: {
|
||||||
@@ -77,7 +79,6 @@ const toc: RawTableOfContents = {
|
|||||||
["cors", "cors", "link:canary"],
|
["cors", "cors", "link:canary"],
|
||||||
["csrf", "csrf", "link:canary"],
|
["csrf", "csrf", "link:canary"],
|
||||||
["trailing-slashes", "trailingSlashes", "link:canary"],
|
["trailing-slashes", "trailingSlashes", "link:canary"],
|
||||||
["tailwindcss", "tailwindcss", "link:canary"],
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
examples: {
|
examples: {
|
||||||
|
|||||||
@@ -36,11 +36,23 @@ export interface ClientSnapshot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface FreshViteConfig {
|
export interface FreshViteConfig {
|
||||||
|
/** Path to main server entry file. Default: main.ts */
|
||||||
serverEntry?: string;
|
serverEntry?: string;
|
||||||
|
/** Path to main client entry file. Default: client.ts */
|
||||||
clientEntry?: string;
|
clientEntry?: string;
|
||||||
|
/** Path to islands directory. Default: ./islands */
|
||||||
islandsDir?: string;
|
islandsDir?: string;
|
||||||
|
/** Path to routes directory. Default: ./routes */
|
||||||
routeDir?: string;
|
routeDir?: string;
|
||||||
|
/**
|
||||||
|
* Ignore file paths matching any of the provided regexes when
|
||||||
|
* crawling the islands and routes directories.
|
||||||
|
*/
|
||||||
ignore?: RegExp[];
|
ignore?: RegExp[];
|
||||||
|
/**
|
||||||
|
* Treat these specifiers as island files. This is used to declare
|
||||||
|
* islands from remote packages.
|
||||||
|
*/
|
||||||
islandSpecifiers?: string[];
|
islandSpecifiers?: string[];
|
||||||
checkImports?: ImportCheck[];
|
checkImports?: ImportCheck[];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ const REDIRECTS: Record<string, string> = {
|
|||||||
"/docs/getting-started/fetching-data":
|
"/docs/getting-started/fetching-data":
|
||||||
"/docs/getting-started/custom-handlers",
|
"/docs/getting-started/custom-handlers",
|
||||||
"/docs/canary/examples/modifying-the-head": "/docs/canary/advanced/head",
|
"/docs/canary/examples/modifying-the-head": "/docs/canary/advanced/head",
|
||||||
|
"/docs/canary/concepts/builder": "/docs/canary/advanced/builder",
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function handler<T>(ctx: Context<T>) {
|
export async function handler<T>(ctx: Context<T>) {
|
||||||
|
|||||||
Reference in New Issue
Block a user