Tailwind in Fresh

Update 2024-05-12

Fresh version 1.6 made it more straightforward to use vanilla Tailwind:

… checking the Tailwind CSS option will now install the Tailwind CSS plugin instead of twind like it did before.

https://fresh.deno.dev/docs/examples/migrating-to-tailwind


While there is support for Twind in Fresh there could be reasons why you would want to use vanilla Tailwind, for example:

Here’s two approaches:

Option 1: Tailwind standalone CLI

Here’s a blog post with some details.

Every version of Tailwind gets released as an executable. Following the steps in the blog post above we can do:

# Get the executable
curl -sLO https://github.com/tailwindlabs/tailwindcss/releases/latest/download/tailwindcss-macos-x64

# Change permissions
chmod +x tailwindcss-macos-x64

# Rename it
mv tailwindcss-macos-x64 tailwindcss

Create the config and CSS file

In tailwind.config.js:

module.exports = {
	content: ["./islands/**/*.tsx", "./components/**/*.tsx", "./routes/**/*.tsx"],
	theme: {
		extend: {},
	},
	plugins: [],
}

In tailwind.css:

@tailwind base;
@tailwind components;
@tailwind utilities;

Development

For development we run Tailwind in --watch mode:

./tailwindcss -i ./tailwind.css -o ./static/styles.css --watch

Then we probably want to use this stylesheet everywhere.

Let’s add it to _app.tsx:

import { AppProps } from "$fresh/server.ts"
import { asset, Head } from "$fresh/runtime.ts"

export default function App({ Component }: AppProps) {
	return (
		<>
			<Head>
				<link rel="stylesheet" href={asset("/styles.css")} />
			</Head>
			<body class="bg-zinc-50 antialiased">
				<Component />
			</body>
		</>
	)
}

Production

For production we want to compile and minify the CSS output:

./tailwindcss -i ./tailwind.css -o ./static/styles.css --minify

Option 2: npm-specifier with deno task

Another approach could be to use the npm: specifier with a deno task.

In deno.json:

{
	"tasks": {
		"dev:css": "deno run -A npm:tailwindcss -i ./tailwindcss.css -o ./static/styles.css --watch",
		"build:css": "deno run -A npm:tailwindcss -i ./tailwindcss.css -o ./static/styles.css --minify"
	}
}