From 2b1de48ff1c356b15de05dc8b3dcaed2db627764 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Fri, 24 May 2024 21:09:51 +0200 Subject: [PATCH] docs: add Fresh 2 migration guide (#2459) Co-authored-by: Luca Casonato --- docs/canary/examples/migration-guide.md | 235 ++++++++++++++++++++++++ docs/toc.ts | 3 +- 2 files changed, 237 insertions(+), 1 deletion(-) create mode 100644 docs/canary/examples/migration-guide.md diff --git a/docs/canary/examples/migration-guide.md b/docs/canary/examples/migration-guide.md new file mode 100644 index 00000000..d1c33288 --- /dev/null +++ b/docs/canary/examples/migration-guide.md @@ -0,0 +1,235 @@ +--- +description: | + Migration guide for Fresh 2.x +--- + +We tried to keep breaking changes in Fresh 2 as minimal as possible, but some +changes need to be updated manually. Fresh 2 comes with many quality of life +[improvements](TODO) that make it easier to extend and adapt Fresh. We've +created this upgrade guide as part of upgrading our own apps here at Deno. + +Use this guide to migrate a Fresh 1.x app to Fresh 2. + +## Applying automatic updates + +Most changes can be applied automatically with the update script. Start the +update by running it in your project directory: + +```sh +deno run -Ar jsr:@fresh/udpate +``` + +This will apply most API changes made in Fresh 2 +[automatically](#automatic-updates) like changing `$fresh/server.ts` imports to +`@fresh/core`. + +## Getting `main.ts` and `dev.ts` ready + +Configuring Fresh doesn't require a dedicated config file anymore. You can +delete the `fresh.config.ts` file. The `fresh.gen.ts` manifest file isn't needed +anymore either. + +```diff + routes/ + dev.ts +- fresh.gen.ts +- fresh.config.ts + main.ts +``` + +Fresh 2 takes great care in ensuring that code that's only needed during +development is separate from production code. This split makes deployments much +smaller, quicker to upload and allows them to boot up much quicker in +production. + +### Updating `dev.ts` + +Development related configuration can be passed to the `Builder` class instance +in `dev.ts`. This file is also where you typically set up development-only +plugins like [tailwindcss](https://tailwindcss.com/). + +The full `dev.ts` file for newly generated Fresh 2 projects looks like this: + +```ts +import { Builder } from "@fresh/core/dev"; +import { tailwind } from "@fresh/plugin-tailwind"; +import { app } from "./main.ts"; + +// Pass development only configuration here +const builder = new Builder({ target: "safari12" }); + +// Example: Enabling the tailwind plugin for Fresh +tailwind(builder, app, {}); + +// Create optimized assets for the browser when +// running `deno run -A dev.ts build` +if (Deno.args.includes("build")) { + await builder.build(app); +} else { + // ...otherwise start the development server + await builder.listen(app); +} +``` + +### Updating `main.ts` + +Similarly, configuration related to running Fresh in production can be passed to +`new App()`: + +```ts +// main.ts +import { App, fsRoutes, staticFiles } from "@fresh/core"; + +export const app = new App() + // Add static file serving middleware + .use(staticFiles()); + +// Enable file-system based routing +await fsRoutes(app, { + loadIsland: (path) => import(`./islands/${path}`), + loadRoute: (path) => import(`./routes/${path}`), +}); + +// If this module is called directly, start the server +if (import.meta.main) { + await app.listen(); +} +``` + +## Merging error pages + +Both the `_500.tsx` and `_404.tsx` template have been unified into a single +`_error.tsx` template. + +```diff + routes/ +- ├── _404.tsx +- ├── _500.tsx ++ ├── _error_.tsx + └── ... +``` + +Inside the `_error.tsx` template you can show different content based on errors +or status codes with the following code: + +```tsx +export default function ErrorPage(props: PageProps) { + const error = props.error; // Contains the thrown Error or HTTPError + if (error instanceof HttpError) { + const status = error.status; // HTTP status code + + // Render a 404 not found page + if (status === 404) { + return

404 - Page not found

; + } + } + + return

Oh no...

; +} +``` + +## Removal of `` component + +The `` component was used in Fresh 1.x to add additional tags to the +`` portion of an HTML document from anywhere on the page. This feature was +removed in preparation and due to performance concerns as it required a complex +machinery in the background to work. + +Instead, passing head-related data is best done via `ctx.state` + +```tsx +// about.tsx +export const handler = { + GET(ctx) { + // Set a route specific data in a handler + ctx.state.title = "About Me"; + return page(); + }, +}; + +// Render that in _app.tsx +export default function AppWrapper(ctx: FreshContext) { + return ( + + + + + {ctx.state.title ? {ctx.state.title} : null} + + + + + + ); +} +``` + +## Update deployment settings + +Fresh 2 requires assets to be build during deployment instead of building them +on demand. Run the `deno task build` command as part of your deployment process. +If you have already set up Fresh's 1.x "Ahead-of-Time Builds", then no changes +are necessary. + +## Automatic updates + +> [info]: The changes listed here are applied automatically when running the +> [`@fresh/udpate`](https://jsr.io/@fresh/update) script and you shouldn't need +> to have to do these yourself. + +### Unified middleware signatures + +Middleware, handler and route component signatures have been unified to all look +the same. Instead of receiving two arguments, they receive one. The `Request` +object is stored on the context object as `ctx.req`. + +```diff +- const middleware = (req, ctx) => new Response("ok"); ++ const middleware = (ctx) => new Response("ok"); +``` + +Same is true for handlers: + +```diff + export const handler = { +- GET(req, ctx) { ++ GET(ctx) { + return new Response("ok"); + }, + }; +``` + +...and async route components: + +```diff +- export default async function MyPage(req: Request, ctx: RouteContext) { ++ export default async function MyPage(props: PageProps) { + const value = await loadFooValue(); + return

foo is: {value}

; + } +``` + +All the various context interfaces have been consolidated and simplified: + +| Fresh 1.x | Fresh 2.x | +| --------------------------------------------- | -------------- | +| `AppContext`, `LayoutContext`, `RouteContext` | `FreshContext` | + +### Context methods + +The `ctx.renderNotFound()` method has been removed in favor of throwing an +`HttpError` instance. This allows all middlewares to optionally participate in +error handling. Other properties have been moved or renamed to make it easier to +re-use existing objects internally as a minor performance optimization. + +| Fresh 1.x | Fresh 2.x | +| ---------------------- | -------------------------- | +| `ctx.renderNotFound()` | `throw new HttpError(404)` | +| `ctx.basePath` | `ctx.config.basePath` | +| `ctx.remoteAddr` | `ctx.info.remoteAddr` | + +## Getting help + +If you run into problems with upgrading your app, reach out to us by creating an +issue here https://github.com/denoland/fresh/issues/new . That way we can +improve this migration guide for everyone. diff --git a/docs/toc.ts b/docs/toc.ts index 609f2b11..02f8f2b5 100644 --- a/docs/toc.ts +++ b/docs/toc.ts @@ -71,7 +71,8 @@ const toc: RawTableOfContents = { title: "Examples", link: "latest", pages: [ - ["migrating-to-tailwind", "Migrating to Tailwind", "link:canary"], + ["migration-guide", "Migration Guide", "link:canary"], + ["migrating-to-tailwind", "Migrating to Tailwind", "link:latest"], ["modifying-the-head", "Modifying the ", "link:latest"], ["writing-tests", "Writing tests", "link:latest"], [