跳至主要內容

使用 Twind 搭配 Deno

Twind 是一個 tailwind-in-js 解决方案,用於使用 Tailwind。Twind 在 Deno 的伺服器環境中特別有用,在該環境中,Tailwind 和 CSS 可以輕鬆地進行伺服器端渲染,生成動態、高效能且有效的 CSS,同時具有使用 Tailwind 進行造型的可用性。

基本範例

在以下範例中,我們將使用 twind 進行伺服器端渲染 HTML 頁面,並將其記錄到主控台。它展示了如何使用分組的 tailwind 類別,並僅使用文件中指定的樣式進行渲染,並且沒有客戶端 JavaScript 來完成 tailwind-in-js

import { extract, install } from "https://esm.sh/@twind/core@1.1.3";
import presetTailwind from "https://esm.sh/@twind/preset-tailwind@1.1.4";

install({
presets: [
presetTailwind(),
{
theme: {
fontFamily: {
sans: ["Helvetica", "sans-serif"],
serif: ["Times", "serif"],
},
},
},
],
});

function renderBody() {
return `<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello from Deno</title>
</head>
<body class="font-sans">
<h1 class="text(3xl blue-500)">Hello from Deno</h1>
<form>
<input name="user">
<button class="text(2xl red-500)">
Submit
</button>
</form>
</body>
</html>
`;
}

function ssr() {
const body = renderBody();
const { html, css } = extract(body);
return html.replace("</head>", `<style data-twind>${css}</style></head>`);
}

console.log(ssr());

https://twind.style/packages/@twind/core#extract