การพัฒนาปลั๊กอิน Vite: การแปลงแบบกำหนดเองและเครื่องมือพัฒนา
Plugin API ของ Vite เป็นชั้นบางๆ เหนือ Rollup ที่ขยายด้วย dev server hooks
โครงสร้างปลั๊กอิน: hooks และวงจรชีวิต
ปลั๊กอิน Vite คือออบเจกต์ธรรมดาที่มีชื่อและเมธอด hook
// Minimal Vite plugin structure
// A plugin is just an object with a name and hooks
export default function myPlugin(options = {}) {
return {
name: 'vite-plugin-my-plugin', // required, shown in warnings/errors
enforce: 'pre', // 'pre' | 'post' | undefined
// Called once when Vite starts
configResolved(config) {
console.log('Vite mode:', config.mode);
},
// Modify Vite config before it resolves
config(config, { command }) {
if (command === 'build') {
return { build: { sourcemap: true } };
}
},
// Transform file contents
transform(code, id) {
if (!id.endsWith('.vue')) return null; // skip non-Vue files
return { code: transformedCode, map: sourceMap };
},
// Resolve module imports to file paths
resolveId(source, importer) {
if (source === 'virtual:my-module') {
return '