Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Plugins

Anatomy of a Vite Plugin

Understand how Vite plugins work: a plain object with a name and hooks such as resolveId, load and transform, plus the order in which Vite calls them.

Almost everything Vite does beyond serving files is done by plugins. Support for React, Vue, TypeScript transforms, CSS handling, asset URLs and JSON imports are all plugins, some built in and some from the community. A plugin is just a JavaScript object with a name and a few functions called hooks. Vite calls those hooks at fixed moments while it turns your source files into browser-ready modules.

Learning the hook model once pays off everywhere. You can read any plugin's source, debug a surprising transform, or write your own in twenty lines. In this lesson you will see the shape of a plugin, the main hooks and their order, and a small runnable stand-in of the pipeline.

Vite itself is not available in the in-browser runners of this site. The code blocks marked "real Vite" are read-only. The runnable examples are small plain-JavaScript stand-ins that copy the idea of Vite's pipeline, so you can see how the hooks fit together.

A plugin is an object

Here is the smallest useful plugin, in real Vite, as read-only code:

JavaScript
// vite.config.js (real Vite)
import { defineConfig } from 'vite';

function hello() {
  return {
    name: 'hello-plugin',
    transform(code, id) {
      if (id.endsWith('.js')) {
        return code.replace('__HELLO__', 'Hello from a plugin');
      }
    },
  };
}

export default defineConfig({
  plugins: [hello()],
});

By convention a plugin is a factory function that returns the object, so users can pass options: hello({ greeting: 'Hi' }). The name is required and shows up in error messages. Plugins that only work with Vite (not with Rollup) are named vite-plugin-something; Rollup-compatible ones are named rollup-plugin-something.

The main hooks

Vite plugins extend the Rollup plugin interface, so they have two groups of hooks.

Hook Runs Purpose
config once, early Change or extend the user's config
configResolved once Read the final config
configureServer dev only Add middleware, watch files, talk to the dev server
transformIndexHtml dev and build Edit or inject into index.html
buildStart / buildEnd build Set up or clean up
resolveId(source, importer) per import Decide which file an import points to
load(id) per module Provide a module's source code
transform(code, id) per module Change a module's source code
handleHotUpdate(ctx) dev only Customize hot updates
generateBundle build Inspect or add output files

The three you will use most are resolveId, load and transform. Think of them as a pipeline for each import: first resolve the name to an id, then load the code for that id, then transform the code.

flowchart LR
  A["import './a.js'"] --> B["resolveId"]
  B --> C["load"]
  C --> D["transform"]
  D --> E["Module served to the browser"]

Every imported module goes through the same three stages. Each plugin may handle a stage or pass.

Returning, passing and the id

A hook that does not want to handle something returns undefined (or null), which means "pass to the next plugin". The first plugin that returns a real value for resolveId or load wins. For transform, every plugin gets its turn and each one receives the previous plugin's output, like a chain of filters.

The id is usually an absolute file path. Query strings are part of it: ./logo.svg?raw has the id /project/logo.svg?raw. Plugins check id to decide whether the file is theirs. A very common bug is matching with id.endsWith('.js') and forgetting that the id might be file.js?v=123; use a proper filter such as createFilter from vite, or strip the query first.

Plugin ordering

Plugins run in this order: Vite's core alias plugin, plugins with enforce: 'pre', Vite's core plugins, normal user plugins, Vite's build plugins, plugins with enforce: 'post', and finally post-build plugins. You set the position with the enforce field:

JavaScript
// real Vite
{
  name: 'run-before-core',
  enforce: 'pre',
  transform(code, id) { /* sees raw source, before TypeScript is compiled */ },
}

Use pre when you need to see untouched source (for example, to preprocess a custom file format before Vite sees it), and post for things that must see the final output, such as a banner. Most plugins need neither.

You can also restrict a plugin to one mode with apply: apply: 'build' or apply: 'serve', or a function that receives the config and the command.

A runnable stand-in pipeline

This stand-in has the same three stages. It is not Vite, but the logic of "first resolveId wins, transform chains" is the same.

JS Stand-in: resolve, load, transform

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that shout saw the output of hello, because transforms chain. In a real project the order of your plugins array decides who goes first.

Plugin context

Inside hooks, this is a plugin context with helpers: this.resolve() to resolve another import, this.warn() and this.error() to report problems, and this.emitFile() to add output files during a build. Prefer these over console.log and throw, because Vite formats them nicely and attaches the module id.

JS Stand-in: first resolveId wins

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a Vite plugin?

    A plugin is a plain object, usually returned by a factory function, with a name and hooks that Vite calls.
  2. 2. In which order are the three module hooks called for each import?

    Vite resolves the import to an id, loads the source for that id, then transforms it.
  3. 3. What does a transform hook return when it does not want to change a file?

    Returning undefined passes the module on unchanged to the next plugin. An empty string would replace the code with nothing.
  4. 4. Which setting runs a plugin before Vite's core plugins?

    enforce: 'pre' puts the plugin before core plugins; enforce: 'post' puts it after the build plugins.

Summary

  • A plugin is an object with a name and hooks, usually made by a factory function.
  • resolveId, load and transform form the pipeline for every module.
  • Returning undefined passes; the first value from resolveId or load wins; transform results chain.
  • enforce (pre/post) and apply (build/serve) control order and mode.
  • Check the id carefully, since it may include a query string.

Next: Writing a Transform Plugin