Skip to content
Grok

Vite Web Workers API

Vite's Web Workers API ช่วยให้คุณกำหนดค่าการทำงานของ Web Workers ในแอปพลิเคชันของคุณ ซึ่งช่วยให้สามารถรันโค้ด JavaScript ในเธรดแยก (background thread) โดยไม่รบกวนการทำงานของเธรดหลัก (main thread)

worker.format

กำหนดรูปแบบของ bundle ที่จะสร้างสำหรับ Web Workers สามารถเลือกได้ระหว่าง 'es' (ES Modules) และ 'iife' (IIFE) ค่าเริ่มต้นคือ 'es' ซึ่งเหมาะสำหรับเบราว์เซอร์รุ่นใหม่ที่รองรับ ES Modules

ts
import { defineConfig } from "vite";

export default defineConfig({
  worker: {
    // 'es' (ES Modules) หรือ 'iife' (Immediately Invoked Function Expression)
    format: "es",
  },
});

คำอธิบายเพิ่มเติม:

  • 'es' (ค่าเริ่มต้น): สร้าง bundle แบบ ES Modules เหมาะสำหรับเบราว์เซอร์รุ่นใหม่
  • 'iife': สร้าง bundle แบบ IIFE (Immediately Invoked Function Expression) ที่เข้ากันได้กับเบราว์เซอร์รุ่นเก่า
  • ควรใช้ 'es' ร่วมกับ type: 'module' เมื่อสร้าง Worker

worker.plugins

กำหนดปลั๊กอินเพิ่มเติมสำหรับการ bundle Worker แยกต่างหากจาก main bundle มีประโยชน์เมื่อต้องการใช้ปลั๊กอินเฉพาะสำหรับ Worker เท่านั้น

ts
import vue from "@vitejs/plugin-vue";
import { defineConfig } from "vite";
import myPlugin from "vite-plugin-my-plugin";

export default defineConfig({
  plugins: [vue()],

  worker: {
    // ใช้ปลั๊กอินเฉพาะสำหรับ Worker
    plugins: [
      myPlugin({
        // ตัวเลือกปลั๊กอิน
      }),
      // ปลั๊กอินอื่นๆ
    ],
  },
});

เมื่อไหร่ควรใช้:

  • เมื่อต้องการใช้ปลั๊กอินเฉพาะสำหรับ Worker
  • เมื่อต้องการกำหนดค่าปลั๊กอินให้แตกต่างระหว่าง main bundle และ Worker
  • เมื่อต้องการเพิ่มความสามารถพิเศษให้กับ Worker

worker.rollupOptions

กำหนดตัวเลือกเพิ่มเติมสำหรับ Rollup ที่ใช้ในการ bundle Worker แยกจาก main bundle ช่วยให้สามารถปรับแต่งการ bundle ได้ละเอียดยิ่งขึ้น

ts
import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";

export default defineConfig({
  worker: {
    rollupOptions: {
      // กำหนด entry points สำหรับ Worker
      input: {
        "worker-main": fileURLToPath(
          new URL("./src/worker/main.js", import.meta.url),
        ),
        "worker-utils": fileURLToPath(
          new URL("./src/worker/utils.js", import.meta.url),
        ),
      },

      output: {
        // กำหนดรูปแบบชื่อไฟล์ output
        entryFileNames: "workers/[name]-[hash].js",
        chunkFileNames: "workers/chunks/[name]-[hash].js",
        assetFileNames: "workers/assets/[name]-[hash][extname]",

        // เปิดใช้งาน source maps
        sourcemap: true,

        // กำหนดรูปแบบของ output
        format: "es",
        inlineDynamicImports: false,
      },

      // กำหนด external dependencies
      external: ["some-heavy-dependency"],

      // กำหนด treeshaking
      treeshake: {
        moduleSideEffects: false,
        propertyReadSideEffects: false,
        tryCatchDeoptimization: false,
      },
    },
  },
});