Dark mode
What is Dependency Pre-Bundling?
Vite จะทำการ pre-bundle dependencies ของ project ของคุณเพื่อเพิ่มประสิทธิภาพในการพัฒนา
js
// vite.config.js
export default {
optimizeDeps: {
// กำหนด dependencies ที่จะถูก pre-bundle
include: ["lodash", "axios"],
},
};
Why Pre-Bundling is Important
- Performance Boost - ลดเวลาในการโหลดระหว่าง development
- CommonJS Conversion - แปลง CommonJS modules เป็น ESM
- Dependency Resolution - แก้ปัญหา version conflicts
How Pre-Bundling Works
Step | Description |
---|---|
1 | Vite ตรวจสอบ dependencies จาก package.json |
2 | ทำการ bundle dependencies เป็นไฟล์เดียว |
3 | เก็บ cache ไว้ในโฟลเดอร์ node_modules/.vite |
js
// ตัวอย่างการ exclude dependencies
import { defineConfig } from "vite";
export default defineConfig({
optimizeDeps: {
exclude: ["some-package"], // ไม่ต้องการให้ bundle package นี้
},
});
Customizing Pre-Bundling
คุณสามารถปรับแต่งการทำงานของ pre-bundling ได้ผ่าน vite.config.js:
optimizeDeps.include
- ระบุ dependencies ที่ต้องการ bundleoptimizeDeps.exclude
- ระบุ dependencies ที่ไม่ต้องการ bundleoptimizeDeps.force
- บังคับให้ทำการ bundle ใหม่ทุกครั้ง
Advanced Configuration Examples
1. Basic Pre-Bundling Setup
js
// vite.config.js
import { defineConfig } from "vite";
export default defineConfig({
optimizeDeps: {
// ระบุ dependencies ที่ต้องการให้ Vite ทำการ pre-bundle
include: [
"vue", // Framework หลัก
"vue-router", // Routing
"pinia", // State management
"axios", // HTTP client
],
// ระบุ dependencies ที่ไม่ต้องการให้ทำการ bundle
exclude: ["moment"], // เนื่องจากขนาดใหญ่และอาจไม่จำเป็นใน development
// บังคับให้ทำการ bundle ใหม่ทุกครั้ง (ใช้เมื่อทดสอบการเปลี่ยนแปลงใน dependencies)
force: false,
},
});
2. Handling CommonJS Dependencies
js
// vite.config.js
export default {
optimizeDeps: {
// บาง packages ยังใช้ CommonJS ซึ่ง Vite จะแปลงให้เป็น ESM อัตโนมัติ
include: [
"lodash", // CommonJS library
"jquery", // อีกตัวอย่างของ CommonJS
"some-cjs-pkg",
],
// สามารถ disable การแปลง CommonJS ได้ถ้าต้องการ
esbuildOptions: {
keepNames: true, // เก็บชื่อเดิมของ functions/classes
plugins: [
// ใส่ esbuild plugins เพิ่มเติมได้ถ้าต้องการ
],
},
},
};
3. Debugging Pre-Bundling
js
// vite.config.js
export default {
optimizeDeps: {
// เปิดโหมด debug เพื่อดูว่ามี dependencies ใดถูก bundle บ้าง
// ตรวจสอบผลลัพธ์ใน terminal เมื่อรัน `vite dev`
needsInterop: true,
// ตัวอย่างการ log dependencies ที่ถูก bundle
esbuildOptions: {
logOverride: {
"unsupported-require-call": "silent", // ปิด warning บางตัว
"missing-export": "warning", // แสดง warning เมื่อ export หาย
},
},
},
};
When to Use Pre-Bundling
- เมื่อใช้ dependencies ขนาดใหญ่
- เมื่อมี dependencies ที่ใช้ CommonJS
- เมื่อต้องการเพิ่มความเร็วในการพัฒนา