Lesson 4 of 6
Plugins & HMR
You'll learn how to add plugins, including the official ones for most frameworks, and how Hot Replacement (HMR) updates the page as you edit without a full reload.
// Popular Vite plugins
// npm install -D @vitejs/plugin-react
// npm install -D @vitejs/plugin-vue
// npm install -D @tailwindcss/vite
// npm install -D vite-plugin-pwa
// npm install -D vite-plugin-svgr
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { VitePWA } from 'vite-plugin-pwa'
import svgr from 'vite-plugin-svgr'
export default defineConfig({
plugins: [
react(),
tailwindcss(),
svgr(), // import SVGs as React components
VitePWA({ // progressive web app support
registerType: 'autoUpdate',
manifest: {
name: 'My App',
short_name: 'App',
theme_color: '#646cff',
icons: [
{ src: '/icon-192.png', sizes: '192x192', type: 'image/png' },
{ src: '/icon-512.png', sizes: '512x512', type: 'image/png' },
],
},
}),
],
})// Writing a simple Vite plugin
import type { Plugin } from 'vite'
function myPlugin(): Plugin {
return {
name: 'my-plugin',
// Transform a file's content
transform(code, id) {
if (!id.endsWith('.txt')) return null
return {
code: `export default ${JSON.stringify(code)}`,
map: null,
}
},
// Inject content into HTML
transformIndexHtml(html) {
return html.replace(
'<head>',
'<head><meta name="generator" content="Vite" />'
)
},
// Hook into server startup
configureServer(server) {
server.middlewares.use('/status', (req, res) => {
res.end(JSON.stringify({ ok: true }))
})
},
}
}
// HMR API — for writing libraries that support HMR
if (import.meta.hot) {
import.meta.hot.accept('./module', (newModule) => {
// Called when module or its dependencies update
updateSomething(newModule)
})
import.meta.hot.dispose(() => {
// Cleanup before module is replaced
cleanup()
})
}Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.