From 912f3782a344c8d5f2281cb3058d60c03719f7c6 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Wed, 10 Jan 2024 10:35:26 +0100 Subject: [PATCH] feat: improve tailwind deployment flow (#2227) By moving folks from `twind` over to the `tailwind` plugin we have traded support questions about "how to get twind autocompletion working?" with "my styles are not showing up in automatic mode". The tailwind plugin has a hard requirement on having a build step. We have documented this at various places and have a guide on how to set everything up, but it's much better if we float those steps from Fresh itself when we detect this. With this PR we will prepare a `.github/workflows/deploy.yml` file already where the user only needs to swap out the project name. When Fresh is started in production mode, the tailwind plugin is active and no snapshot files were loaded, then we print a helpful hint to the console: ```sh No pre-compiled tailwind styles found. Did you forget to run "deno task build" prior to starting the production server? ``` When we are running inside Deno Deploy this PR goes one step further. Since it is the first time many users might use Deno Deploy we'll also show a simple page that shows how to finish the tailwind setup. I've intentionally tried to not present this as a warning but rather as a "finishing" step to avoid scaring users off. It's not the prettiest page, but it's good enough for now. Screenshot 2024-01-09 at 23 41 27 Fixes https://github.com/denoland/fresh/issues/2223 --- init.ts | 7 +++ src/dev/imports.ts | 35 +++++++++++ src/server/config.ts | 1 + src/server/context.ts | 57 ++++++++++++++++-- src/server/tailwind_aot_error_page.tsx | 80 ++++++++++++++++++++++++++ src/server/types.ts | 1 + tests/init_test.ts | 1 + tests/tailwind_test.ts | 64 ++++++++++++++++++++- tests/test_utils.ts | 15 ++++- 9 files changed, 253 insertions(+), 8 deletions(-) create mode 100644 src/server/tailwind_aot_error_page.tsx diff --git a/init.ts b/init.ts index 56035e96..2d82fbae 100644 --- a/init.ts +++ b/init.ts @@ -2,6 +2,7 @@ import { basename, colors, join, parse, resolve } from "./src/dev/deps.ts"; import { error } from "./src/dev/error.ts"; import { collect, ensureMinDenoVersion, generate } from "./src/dev/mod.ts"; import { + AOT_GH_ACTION, dotenvImports, freshImports, tailwindImports, @@ -313,6 +314,12 @@ if (useTailwind) { join(resolvedDirectory, "tailwind.config.ts"), TAILWIND_CONFIG_TS, ); + const ghWorkflowDir = join(resolvedDirectory, ".github", "workflows"); + await Deno.mkdir(ghWorkflowDir, { recursive: true }); + await Deno.writeTextFile( + join(ghWorkflowDir, "deploy.yml"), + AOT_GH_ACTION, + ); } const NO_TAILWIND_STYLES = ` diff --git a/src/dev/imports.ts b/src/dev/imports.ts index 81b9b52d..27f48afb 100644 --- a/src/dev/imports.ts +++ b/src/dev/imports.ts @@ -31,3 +31,38 @@ export function tailwindImports(imports: Record) { export function dotenvImports(imports: Record) { imports["$std/"] = `https://deno.land/std@${RECOMMENDED_STD_VERSION}/`; } + +export const AOT_GH_ACTION = `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 +`; diff --git a/src/server/config.ts b/src/server/config.ts index 803a538b..c45513d6 100644 --- a/src/server/config.ts +++ b/src/server/config.ts @@ -125,6 +125,7 @@ export async function getInternalFreshState( config: internalConfig, manifest, loadSnapshot: !isLegacyDev && !config.dev, + didLoadSnapshot: false, denoJsonPath, denoJson, build: false, diff --git a/src/server/context.ts b/src/server/context.ts index dcce8c3b..aafdc355 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -7,7 +7,7 @@ import { DEV_ERROR_OVERLAY_URL, JS_PREFIX, } from "./constants.ts"; -import { BUILD_ID } from "./build_id.ts"; +import { BUILD_ID, DENO_DEPLOYMENT_ID } from "./build_id.ts"; import { ErrorPage, @@ -44,6 +44,7 @@ import { loadAotSnapshot } from "../build/aot_snapshot.ts"; import { ErrorOverlay } from "./error_overlay.tsx"; import { withBase } from "./router.ts"; import { PARTIAL_SEARCH_PARAM } from "../constants.ts"; +import TailwindErrorPage from "$fresh/src/server/tailwind_aot_error_page.tsx"; const DEFAULT_CONN_INFO: ServeHandlerInfo = { localAddr: { transport: "tcp", hostname: "localhost", port: 8080 }, @@ -84,7 +85,10 @@ export async function getServerContext(state: InternalFreshState) { let snapshot: Builder | BuildSnapshot | Promise | null = null; if (state.loadSnapshot) { const loadedSnapshot = await loadAotSnapshot(config); - if (loadedSnapshot !== null) snapshot = loadedSnapshot; + if (loadedSnapshot !== null) { + snapshot = loadedSnapshot; + state.didLoadSnapshot = true; + } } const finalSnapshot = snapshot ?? new EsbuildBuilder({ @@ -323,7 +327,7 @@ export class ServerContext { } { const internalRoutes: router.Routes = {}; const staticRoutes: router.Routes = {}; - const routes: router.Routes = {}; + let routes: router.Routes = {}; const assetRoute = withBase( `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`, @@ -455,7 +459,7 @@ export class ServerContext { } } - const otherHandler: router.Handler = (req, ctx) => { + let otherHandler: router.Handler = (req, ctx) => { ctx.render = (data) => { ctx.data = data; return renderNotFound(req, ctx); @@ -540,6 +544,51 @@ export class ServerContext { }; } + // This page is shown when the user uses the tailwindcss plugin and + // hasn't configured AOT builds. + if ( + !this.#state.config.dev && + this.#state.loadSnapshot && !this.#state.didLoadSnapshot && + this.#state.config.plugins.some((plugin) => plugin.name === "tailwind") + ) { + if (DENO_DEPLOYMENT_ID !== undefined) { + // Don't fail hard here and instead rewrite all routes to a special + // error route. Otherwise the first user experience of deploying a + // Fresh project would be pretty disruptive + console.error( + "%cError: Ahead of time builds not configured but required by the tailwindcss plugin.\nTo resolve this error, set up ahead of time builds: https://fresh.deno.dev/docs/concepts/ahead-of-time-builds", + "color: red", + ); + console.log(); + + // Clear all routes so that everything redirects to the tailwind + // error page. + routes = {}; + + const freshErrorPage = genRender({ + appWrapper: false, + inheritLayouts: false, + component: TailwindErrorPage, + csp: false, + name: "tailwind_error_route", + pattern: "*", + url: "", + baseRoute: toBaseRoute("*"), + handler: (_req: Request, ctx: FreshContext) => ctx.render(), + }, STATUS_CODE.InternalServerError); + otherHandler = (req, ctx) => { + const render = freshErrorPage(req, ctx); + return render(); + }; + } else { + // Not on Deno Deploy. The user likely forgot to run `deno task build` + console.warn( + '%cNo pre-compiled tailwind styles found.\n\nDid you forget to run "deno task build" prior to starting the production server?', + "color: yellow", + ); + } + } + return { internalRoutes, staticRoutes, routes, otherHandler, errorHandler }; } diff --git a/src/server/tailwind_aot_error_page.tsx b/src/server/tailwind_aot_error_page.tsx new file mode 100644 index 00000000..68066922 --- /dev/null +++ b/src/server/tailwind_aot_error_page.tsx @@ -0,0 +1,80 @@ +import { AOT_GH_ACTION } from "../dev/imports.ts"; + +const LINK = "https://fresh.deno.dev/docs/concepts/ahead-of-time-builds"; + +export default function TailwindErrorPage() { + return ( +
+
+

Finish setting up Fresh

+

+ The tailwindcss{" "} + plugin requires ahead of time builds to be set up for production + usage. To finish the setup, follow these steps: +

+
    +
  1. + Go to your project in Deno Deploy and click the{" "} + Settings tab. +
  2. +
  3. + Set Git-Integration to GitHub Action.
    + + Unlink the repository first if it is already linked via{" "} + Automatic and re-link it again. + +
  4. +
  5. + Add the file .github/workflows/deploy.yml{" "} + to your repository with the following contents:
    + + +
    {AOT_GH_ACTION}
    +
    +
  6. +
  7. + Copy the project name under Setting {">"} Project Name + {" "} + and replace "example project" with your actual project name in{" "} + .github/workflows/deploy.yml. +
  8. +
  9. + Commit the file you created and merge it into the main + {" "} + branch. This will trigger a new deployment and finish the setup. +
  10. +
+

+ See the detailed guide here: {LINK}. +

+
+