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.

<img width="892" alt="Screenshot 2024-01-09 at 23 41 27"
src="https://github.com/denoland/fresh/assets/1062408/9bf2a61b-5551-4d8e-bdf8-b498072f8e98">


Fixes https://github.com/denoland/fresh/issues/2223
This commit is contained in:
Marvin Hagemeister
2024-01-10 10:35:26 +01:00
committed by GitHub
parent 8d01051b5b
commit 912f3782a3
9 changed files with 253 additions and 8 deletions
+7
View File
@@ -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 = `
+35
View File
@@ -31,3 +31,38 @@ export function tailwindImports(imports: Record<string, string>) {
export function dotenvImports(imports: Record<string, string>) {
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
`;
+1
View File
@@ -125,6 +125,7 @@ export async function getInternalFreshState(
config: internalConfig,
manifest,
loadSnapshot: !isLegacyDev && !config.dev,
didLoadSnapshot: false,
denoJsonPath,
denoJson,
build: false,
+53 -4
View File
@@ -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<BuildSnapshot> | 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 };
}
+80
View File
@@ -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 (
<div class="frsh-error-page">
<div style="max-width: 48rem; padding: 2rem 1rem; margin: 0 auto; font-family: sans-serif">
<h1>Finish setting up Fresh</h1>
<p style="line-height: 1.6;margin-bottom: 1rem;">
The <b>tailwindcss</b>{" "}
plugin requires ahead of time builds to be set up for production
usage. To finish the setup, follow these steps:
</p>
<ol style="line-height: 1.6; margin-bottom: 1.5rem">
<li>
Go to your project in Deno Deploy and click the{" "}
<code>Settings</code> tab.
</li>
<li>
Set Git-Integration to <code>GitHub Action</code>.<br />
<i style="display: block; font-style: italic; color: gray;">
Unlink the repository first if it is already linked via{" "}
<code>Automatic</code> and re-link it again.
</i>
</li>
<li>
Add the file <code>.github/workflows/deploy.yml</code>{" "}
to your repository with the following contents:<br />
<span style="background: #f0f0f0;display: block; position: relative;">
<button
id="copy-gh-action"
style="position: absolute; top: .5rem; right: .5rem;z-index: 100"
>
copy code
</button>
<pre style="height: 200px; overflow: auto;padding: 1rem;"><code>{AOT_GH_ACTION}</code></pre>
</span>
</li>
<li>
Copy the project name under <code>Setting {">"} Project Name</code>
{" "}
and replace "example project" with your actual project name in{" "}
<code>.github/workflows/deploy.yml</code>.
</li>
<li>
Commit the file you created and merge it into the <code>main</code>
{" "}
branch. This will trigger a new deployment and finish the setup.
</li>
</ol>
<p>
See the detailed guide here: <a href={LINK}>{LINK}</a>.
</p>
</div>
<script
dangerouslySetInnerHTML={{
__html: `
const copyBtn = document.querySelector("#copy-gh-action");
if (copyBtn) {
let timeout;
const text = copyBtn.textContent;
copyBtn.addEventListener("click", async () => {
copyBtn.textContent = "copied!";
clearTimeout(timeout);
timeout = setTimeout(() => {
copyBtn.textContent = text
}, 2000);
const code = \`${AOT_GH_ACTION}\`;
await navigator.clipboard.writeText(code);
})
}
`,
}}
/>
</div>
);
}
+1
View File
@@ -101,6 +101,7 @@ export interface InternalFreshState {
config: ResolvedFreshConfig;
manifest: Manifest;
loadSnapshot: boolean;
didLoadSnapshot: boolean;
denoJsonPath: string;
denoJson: DenoConfig;
build: boolean;
+1
View File
@@ -185,6 +185,7 @@ Deno.test({
"/.vscode/settings.json",
"/.vscode/extensions.json",
"/.gitignore",
"/.github/workflows/deploy.yml",
];
await t.step("check generated files", async () => {
+62 -2
View File
@@ -1,5 +1,12 @@
import { runBuild, withFakeServe } from "./test_utils.ts";
import { assert, assertStringIncludes } from "./deps.ts";
import { fetchHtml, runBuild, withFakeServe, withFresh } from "./test_utils.ts";
import {
assert,
assertStringIncludes,
dirname,
join,
TextLineStream,
} from "./deps.ts";
import { assertEquals } from "$std/assert/assert_equals.ts";
Deno.test("TailwindCSS - dev mode", async () => {
await withFakeServe("./tests/fixture_tailwind/dev.ts", async (server) => {
@@ -62,3 +69,56 @@ Deno.test("TailwindCSS - middleware only css", async () => {
{ loadConfig: true },
);
});
Deno.test("TailwindCSS - missing snapshot warning", async () => {
const dir = dirname(import.meta.url);
const out = await new Deno.Command(Deno.execPath(), {
args: ["run", "-A", join(dir, "./fixture_tailwind/main.ts")],
stdout: "piped",
stderr: "piped",
}).spawn();
const lines: ReadableStream<string> = out.stderr
.pipeThrough(new TextDecoderStream())
.pipeThrough(new TextLineStream());
let found = false;
// @ts-ignore yes it does
for await (const line of lines.values({ preventCancel: true })) {
if (!found && line.includes("No pre-compiled tailwind styles found")) {
found = true;
break;
}
}
try {
assert(found, "Tailwind compile warning was not logged");
} finally {
await out.stdout.cancel();
out.kill("SIGTERM");
await out.status;
// Drain the lines stream
for await (const _ of lines) { /* noop */ }
}
});
Deno.test("TailwindCSS - missing snapshot on Deno Deploy", async () => {
await withFresh(
{
name: "./tests/fixture_tailwind/main.ts",
options: {
env: {
DENO_DEPLOYMENT_ID: "foo",
},
},
},
async (address) => {
const doc = await fetchHtml(address);
assertEquals(
doc.querySelector("h1")?.textContent,
"Finish setting up Fresh",
);
},
);
});
+13 -2
View File
@@ -218,11 +218,22 @@ export async function withFresh(
}
export async function withPageName(
name: string,
name: string | { name: string; options: Omit<Deno.CommandOptions, "args"> },
fn: (page: Page, address: string) => Promise<void>,
) {
let file: string;
let options = {};
if (typeof name === "object") {
file = name.name;
options = name.options ?? {};
} else {
file = name;
}
const { lines, serverProcess, address } = await startFreshServer({
args: ["run", "-A", name],
...options,
args: ["run", "-A", file],
});
try {