Dark mode
Nuxt.js Assets
ภาพรวม
Nuxt ใช้โฟลเดอร์หลัก 2 โฟลเดอร์ในการจัดการไฟล์ทรัพยากร:
โฟลเดอร์ | คำอธิบาย |
---|---|
public/ | ไฟล์ที่ต้องการให้เข้าถึงได้โดยตรงจาก root URL |
assets/ | ไฟล์ที่ต้องการให้ผ่านการประมวลผลโดย build tool |
Public Directory
ไฟล์ในโฟลเดอร์ public/
จะถูกให้บริการจาก root URL โดยตรงโดยไม่ผ่านการประมวลผลใดๆ เหมาะสำหรับไฟล์ที่ต้องการ URL คงที่
โครงสร้างโฟลเดอร์:
bash
public/
images/
logo.png
favicon.ico
robots.txt
การใช้งานในโค้ด:
vue
<template>
<div>
<!-- การอ้างอิงไฟล์จาก public/ -->
<img src="/images/logo.png" alt="Logo">
<!-- หรือใช้ URL เต็ม -->
<img :src="`${config.public.baseUrl}/images/logo.png`" alt="Logo">
</div>
</template>
<script setup>
const config = useRuntimeConfig();
</script>
Assets Directory
ไฟล์ในโฟลเดอร์ assets/
จะถูกประมวลผลโดย build tool (Vite หรือ webpack) เหมาะสำหรับไฟล์ที่ต้องการการประมวลผลก่อนใช้งาน เช่น SCSS, TypeScript, หรือรูปภาพที่ต้องการ optimization
โครงสร้างโฟลเดอร์:
bash
assets/
styles/
main.scss
images/
hero.jpg
fonts/
custom.woff2
การใช้งานในโค้ด:
vue
<template>
<div>
<!-- การอ้างอิงไฟล์จาก assets/ -->
<img src="~/assets/images/hero.jpg" alt="Hero">
</div>
</template>
<style scoped>
/* การนำเข้าไฟล์ SCSS */
@import "~/assets/styles/main.scss";
</style>
ข้อแตกต่างระหว่าง public/ และ assets/
ลักษณะ | public/ | assets/ |
---|---|---|
การประมวลผล | ไม่มีการประมวลผล | ผ่านการประมวลผลโดย build tool |
การอ้างอิง | ใช้ / นำหน้า | ใช้ ~/assets/ |
เหมาะสำหรับ | ไฟล์ขนาดใหญ่, favicon.ico, robots.txt | รูปภาพ, สไตล์, ฟอนต์ ที่ต้องการ optimization |
การแคช | ใช้ HTTP cache ตามปกติ | มี hash ในชื่อไฟล์เพื่อจัดการ cache |
ตัวอย่างการใช้งานร่วมกับ CSS
vue
<template>
<div class="hero">
<h1>Welcome to Nuxt</h1>
</div>
</template>
<style scoped>
.hero {
/* ใช้ URL ของรูปจาก assets */
background-image: url("~/assets/images/background.jpg");
background-size: cover;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
color: white;
}
</style>
สรุป
- ใช้
public/
สำหรับไฟล์ที่ต้องการ URL คงที่และไม่ต้องการการประมวลผล - ใช้
assets/
สำหรับไฟล์ที่ต้องการการประมวลผลหรือ optimization - ใช้
~/assets/
ในการอ้างอิงไฟล์ใน components - ใช้
/
ในการอ้างอิงไฟล์ใน public directory
TIP
- ไฟล์ใน
assets/
จะถูกบีบอัดและเพิ่ม hash ในชื่อไฟล์อัตโนมัติ - ไฟล์ใน
public/
เหมาะสำหรับไฟล์ที่ต้องมีชื่อไฟล์คงที่ เช่นrobots.txt
หรือsitemap.xml