Skip to content

Static Asset Handling in Vite

การจัดการไฟล์ Static Asset ใน Vite

การนําเข้าไฟล์ (Importing Assets)

Vite สามารถจัดการไฟล์ static assets ได้หลากหลายรูปแบบ โดยมีวิธีการใช้งานดังนี้

การ Import รูปภาพ

js
// นําเข้ารูปภาพโดยตรง
import imgUrl from "./img/hero.png";

// ใช้งานใน JSX/Template
<img src={imgUrl} alt="hero" />;

การ Import ไฟล์อื่นๆ

js
// นําเข้าไฟล์ CSS
import "./styles.css";

// นําเข้าไฟล์ JSON
import data from "./data.json";

Public Directory

โฟลเดอร์ public/ ใช้สําหรับเก็บไฟล์ที่:

  • ไม่ต้องผ่านการ process
  • ต้องคงชื่อไฟล์เดิมไว้
  • ต้องอ้างอิง URL แบบ absolute path

วิธีใช้งาน Public Directory

  1. วางไฟล์ใน public/
  2. อ้างอิงโดยใช้ root path /
html
<!-- ถ้าไฟล์อยู่ที่ public/icon.png -->
<img src="/icon.png" alt="Icon" />

URL Handling

Vite จัดการ URL ในรูปแบบต่างๆ:

Static Asset URL

js
// URL จะถูก resolve อัตโนมัติ
.my-bg { background: url('./hero.png') }

Base URL

js
// ตั้งค่า base URL ใน vite.config.js
export default {
  base: "/my-app/",
};

ตัวอย่างการใช้งาน (Examples)

การ Import รูปภาพแบบ Dynamic

js
const images = import.meta.glob("./images/*.png");

// ใช้งาน
for (const path in images) {
  images[path]().then((mod) => {
    // handle image URL in mod.default
  });
}

การจัดการไฟล์ SVG

jsx
// Import เป็น Component
import IconComponent from "./icon.svg?component";

// Import เป็น URL
import iconUrl from "./icon.svg";

// ใช้งาน
<IconComponent />;
<img src={iconUrl} />;

การตั้งค่า Asset Size Limit

js
// vite.config.js
export default {
  build: {
    assetsInlineLimit: 4096, // 4kb
  },
};

ข้อควรระวัง

  1. ไฟล์ใน public/ จะไม่ผ่านการ process หรือ bundle
  2. อย่าลืมใส่ alt attribute สําหรับรูปภาพ
  3. ระวังเรื่อง case-sensitive ในการอ้างอิงไฟล์
  4. ตรวจสอบ base URL เมื่อ deploy