Skip to content
Grok

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

  1. Performance Boost - ลดเวลาในการโหลดระหว่าง development
  2. CommonJS Conversion - แปลง CommonJS modules เป็น ESM
  3. Dependency Resolution - แก้ปัญหา version conflicts

How Pre-Bundling Works

StepDescription
1Vite ตรวจสอบ 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 ที่ต้องการ bundle
  • optimizeDeps.exclude - ระบุ dependencies ที่ไม่ต้องการ bundle
  • optimizeDeps.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
  • เมื่อต้องการเพิ่มความเร็วในการพัฒนา