DEV Community

Cover image for ลดขนาด tailwindcss ไฟล์ด้วย Purge
Coding with his cats
Coding with his cats

Posted on

4

ลดขนาด tailwindcss ไฟล์ด้วย Purge

tailwindcss เป็น css framework ที่ช่วยให้เราเขียน css ได้ง่ายและรวดเร็วโดยไม่ถูกตีกรอบเรื่อง design กำลังได้รับความนิยมอย่างมากในปัจจุบัน

แต่ข้อเสียสำคัญของ tailwindcss ก็คือขนาดไฟล์ที่ใหญ่มาก ประมาณ 1-1.2MB ถ้าไม่ตัดอะไรออกเลย วิธีแก้ก่อนหน้านี้คือการใช้ PurgeCSS ในการตัด class ที่ไม่ได้ใช้ทิ้ง ซึ่งก็ไม่ได้ยากอะไรแต่ก็ต้องยุ่งยากขึ้นในการติดตั้งและ config ตัว PurgeCSS ให้ทำงานได้ถูกต้อง

คนทำ tailwindcss เขาก็รู้แหละ ใน version 1.4 เป็นต้นมา เขาก็เลย built-in PurgeCSS มาเลย! ทีนี้สบาย ง่าย จบใน config เดียว

ตัวอย่าง tailwind.config.js ที่เมื่อเราทำ production build (NODE_ENV=production) มันจะเข้าไปดูว่ามี class อะไรถูกใช้บ้าง (ในกรณีนี้คือเข้าไปดูใน elm ไฟล์และ HTML)

module.exports = {
  purge: ["./src/**/*.html", "./src/**/*.elm"],
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
};

เมื่อรัน build

➜ npx tailwindcss build src/index.tailwind.css -o src/index.css

   tailwindcss 1.4.6

   🚀 Building... src/index.tailwind.css

   ✅ Finished in 1.8 s
   📦 Size: 29.12KB
   💾 Saved to src/index.css

จาก 1.2MB เหลือแค่ 30KB เท่านั้นเอง

ข้อควรระวัง

สิ่งที่ PurgeCSS ทำให้คือมันเข้าไปดูว่าใน source code เรามี class ของ tailwindcss อันไหนอยู่บ้างแล้วลบที่เหลือออกให้ แต่มันจะตรวจไม่เจอ ถ้าเราไม่ได้ใส่ชื่อ class ไว้แบบเต็ม ๆ

แบบนี้จะไม่เจอเพราะประกอบชื่อ class จากค่าคงที่

class ("bg-teal-" ++ shade) -- shade คือค่าน้ำหนักสี

แบบนี้ถึงจะเจอเพราะใช้ชื่อ class ของ tailwindcss แบบเต็ม ๆ

class
  (case shade of
    Light -> "bg-teal-200"
    Normal -> "bg-teal-400"

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay