Vite 플러그인 개발: 커스텀 변환 및 개발 도구 구축
Vite의 플러그인 API는 Rollup 위에 얇게 쌓인 레이어로, 개발 서버 훅이 확장되어 있습니다.
플러그인 해부: 훅과 라이프사이클
Vite 플러그인은 name과 훅 메서드를 가진 간단한 객체입니다.
// 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 '