ViVite · Lesson 4 of 6

Plugins & HMR

Vite's plugin API is based on Rollup's, extended with Vite-specific hooks. Most frameworks have an official Vite plugin. HMR (Hot Module Replacement) updates the browser in milliseconds without a full page reload.

TypeScript
// 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' },
        ],
      },
    }),
  ],
})
TypeScript
// 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()
  })
}
◆ Note
Vite's HMR works out of the box for Vue and React (via their plugins). For vanilla JS, you need to handle `import.meta.hot` manually. HMR preserves component state during updates — you edit a button's style and the button updates instantly without losing what you typed in a nearby form.