Skip to content

Performance & Optimization

Tailwind CSS 4 มี Oxide Engine ที่เร็วมาก แต่ยังมีเทคนิคเพิ่มเติมสำหรับ production


Tailwind v4 purge อัตโนมัติ — เฉพาะ classes ที่ใช้จริงเท่านั้นที่จะอยู่ใน CSS

~15MB+ (ทุก utilities)
~10-30KB (เฉพาะที่ใช้)

ไม่ต้องทำอะไร — Oxide Engine จัดการให้อัตโนมัติ


Tailwind scan ไฟล์เหล่านี้โดยอัตโนมัติ:

  • *.html
  • *.js, *.jsx, *.ts, *.tsx
  • *.vue, *.svelte, *.astro
  • *.mdx
@import "tailwindcss";
/* Scan ไฟล์เพิ่มเติม */
@source "../node_modules/my-ui-lib/components";
@source "../content/**/*.md";

❌ ไม่ดี (ไม่ถูก detect)

Section titled “❌ ไม่ดี (ไม่ถูก detect)”
// Tailwind จะไม่เห็น class นี้!
const color = isActive ? "blue" : "gray";
<div className={`bg-${color}-500`}>...</div>;
// เขียนเต็มๆ
<div className={isActive ? "bg-blue-500" : "bg-gray-500"}>...</div>

✅ ดีกว่า (ใช้ object mapping)

Section titled “✅ ดีกว่า (ใช้ object mapping)”
const colorMap = {
primary: "bg-blue-500 text-white",
secondary: "bg-gray-500 text-white",
danger: "bg-red-500 text-white",
};
<div className={colorMap[variant]}>...</div>;

~5ms
# Oxide Engine เร็วมาก
Terminal window
npm run build
# Typical output:
# CSS: 25KB (gzipped: 6KB)
# Build time: <1s

ถ้าใช้ library ที่สร้าง CSS dynamically:

// ❌ Avoid runtime CSS generation
import styled from "styled-components";
// ✅ Use Tailwind classes instead
<div className="bg-blue-500 hover:bg-blue-600" />;

เหตุผล: Tailwind generates CSS at build time = 0 runtime cost


vite.config.js
export default {
build: {
cssCodeSplit: true,
rollupOptions: {
output: {
assetFileNames: "assets/[name].[hash].[ext]",
},
},
},
};

สำหรับ pages ที่ต้องการ performance สูงสุด:

<head>
<!-- Inline critical CSS -->
<style>
/* Critical above-the-fold styles */
</style>
<!-- Lazy load full CSS -->
<link
rel="preload"
href="/styles.css"
as="style"
onload="this.onload=null;this.rel='stylesheet'"
/>
</head>

Terminal window
# After build
ls -la dist/assets/*.css
# หรือใช้ gzip size
gzip -c dist/assets/style.css | wc -c
MetricTarget
CSS size (raw)< 50KB
CSS size (gzip)< 10KB
Build time< 2s

ถ้าใช้ UI library:

/* Import เฉพาะที่ใช้ */
@source "../node_modules/my-lib/components/Button";
@source "../node_modules/my-lib/components/Modal";

ItemStatus
ใช้ Tailwind v4 (Oxide Engine)
ไม่มี dynamic class names
CSS gzipped < 10KB
Build time < 2s
ใช้ CSS caching
Remove unused @source paths

Do ✅Don’t ❌
เขียน class names เต็มๆใช้ template strings สร้าง class
ใช้ object mapping สำหรับ variantsทำ string concatenation
ลบ @source ที่ไม่ใช้Keep paths ที่ไม่จำเป็น
Check bundle size หลัง buildAssume มันเล็กอยู่แล้ว

  1. Tailwind v4 เร็วมาก — ส่วนใหญ่ไม่ต้อง optimize อะไรเลย
  2. Focus on code patterns — หลีกเลี่ยง dynamic classes
  3. Measure before optimize — ตรวจ actual bundle size ก่อน