Using plugins and framework integrations

Vite · Advanced · 10 min

Framework support, legacy browsers, PWAs and much more come from plugins.

Vite itself handles JS, TS, CSS and assets; everything else is a plugin in the plugins array.

  • Official plugins: @vitejs/plugin-react (Fast Refresh, JSX), @vitejs/plugin-react-swc, @vitejs/plugin-vue, @vitejs/plugin-vue-jsx, @vitejs/plugin-legacy. Svelte, Solid, Preact and Qwik maintain their own.
  • Community plugins cover PWAs, SVG-as-component, image optimization, bundle visualizers, and more.

Vite plugins are a superset of the Rollup plugin interface, so many Rollup (and Rolldown) plugins work unchanged. Vite-specific hooks add dev-server and HTML integration.

Controlling plugins:

  • enforce: "pre" | "post" changes ordering relative to Vite's core plugins (e.g. a plugin that must see raw source runs pre).
  • apply: "serve" | "build" (or a function) limits a plugin to dev or build.
  • Arrays are flattened, and falsy entries are ignored, so mode === "analyze" && visualizer() works.

Frameworks such as Nuxt, SvelteKit, Astro, React Router (framework mode), TanStack Start and Vike are themselves Vite plugins plus conventions. Frameworks often configure Vite for you, so check their config hooks before adding plugins directly.

Keep the list short: each plugin runs on every transformed module, and slow plugins are a common cause of slow dev servers.

Example

// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import legacy from "@vitejs/plugin-legacy";
import { visualizer } from "rollup-plugin-visualizer";

export default defineConfig(({ mode }) => ({
  plugins: [
    react(),                                   // Fast Refresh + JSX
    legacy({ targets: ["defaults", "not IE 11"] }), // polyfilled legacy chunks
    mode === "analyze" && visualizer({ open: true, filename: "stats.html" }),
    {
      name: "only-in-dev",
      apply: "serve",                          // skip during vite build
      configureServer() { console.log("dev server starting"); },
    },
  ],
}));
// npx vite build --mode analyze  -> opens a treemap of the bundle

Remember

  • Plugins add frameworks and features; Vite plugins extend Rollup's interface
  • enforce orders plugins, apply limits them to dev or build
  • Falsy entries in plugins are ignored
  • Meta-frameworks are Vite plugins with conventions

Watch out for

  • Stacking many heavy plugins and blaming Vite for slow transforms.

Check yourself

  1. How do you make a plugin run only for `vite build`?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: vite.dev/guide/using-plugins