Tworzenie wtyczek Vite: niestandardowe transformacje i narzędzia deweloperskie
API wtyczek Vite to cienka warstwa nad Rollupem, rozszerzona o hooki serwera deweloperskiego.
Anatomia wtyczki: hooki i cykl życia
Wtyczka Vite to prosty obiekt z nazwą i metodami 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 '