The Plugin Pipeline and Writing Your Own

The Plugin Pipeline and Writing Your Own in Vite: A dry-cleaning plant is one long conveyor.

The Analogy: The Dry-Cleaner's Processing Line

A dry-cleaning plant is one long conveyor. A garment enters at intake and rides past a row of specialized stations - a spotter, a press, a mender, a bagger - and each one glances at the ticket and either does its single job or lets the piece ride past untouched. No station does everything; the line works because each does one thing well and hands the garment along.

The intake clerk is the resolver: you hand over a vague claim like "the wool coat from Tuesday" and they turn it into an exact rack position. A runner then pulls the physical garment onto the belt, the way a loader fetches a module's source. The spotter and the press rewrite the garment's state the way a transform rewrites code, and any station that sees a ticket outside its specialty simply waves it on - the equivalent of a hook returning "not mine."

Position on the belt decides everything. A pre-treatment station is bolted on before the main wash so stains loosen first; final inspection sits at the very end. Some stations run only for one kind of order - an alterations bench for tailoring tickets, a same-day lane for rush jobs. And when a ticket calls for a shop-made item with no garment behind it, a replacement belt or a loaner cover, the intake clerk recognizes the code and the fabrication bench produces it, tagging it a distinct internal color so no other station goes hunting for a customer garment.

The line breaks the day someone bolts the press after the folding-and-bagging station. By then each garment is already folded in plastic, so the press never sees the wrinkles it was built to remove and every order ships creased. Nothing is mechanically broken - each station still works - but the order is wrong, which is exactly the failure you get when a plugin's enforce is set wrong and its transform runs after another plugin has already rewritten or consumed the code.


Syntax or Core Structure

A plugin is a plain object, or a function that returns one, with a name and one or more hooks. Vite runs it inside Rollup's plugin system and adds a handful of Vite-only hooks on top.

export default function myPlugin() {
  return {
    name: 'my-plugin',   // required; appears in errors and warnings
    enforce: 'pre',      // 'pre' | 'post' | undefined (middle group)
    apply: 'serve',      // 'serve' | 'build' | undefined (both)
    transform(code, id) {
      return null;       // null = leave this module untouched
    },
  };
}

You register plugins in the plugins array in vite.config.js. Nested arrays and falsy entries are allowed, so a conditional plugin is just mode === 'production' && myPlugin().

Vite does not run plugins in array order. It sorts them into three groups - everything marked enforce: 'pre' first, then the unmarked middle group, then enforce: 'post' - and preserves your declaration order only within a group.

const plugins = [
  { name: 'core-esbuild' },                  // normal
  { name: 'inject-banner', enforce: 'pre' },
  { name: 'bundle-report', enforce: 'post' },
  { name: 'strip-debug' },                   // normal
  { name: 'alias-early', enforce: 'pre' },
];

const rank = (p) => (p.enforce === 'pre' ? 0 : p.enforce === 'post' ? 2 : 1);
const ordered = plugins
  .map((p, i) => ({ p, i }))
  .sort((a, b) => rank(a.p) - rank(b.p) || a.i - b.i)
  .map((x) => x.p.name + ' (' + (x.p.enforce || 'normal') + ')');

ordered.forEach((line, i) => console.log((i + 1) + '. ' + line));

Output:

1. inject-banner (pre)
2. alias-early (pre)
3. core-esbuild (normal)
4. strip-debug (normal)
5. bundle-report (post)

Both pre plugins run first, in the order you declared them, then the middle group, then post. Fix this rule in your head and most "my hook ran at the wrong time" confusion disappears.


Technical Depth: How the Hook Pipeline Processes a Module

The hooks, grouped by job

The hooks fall into three jobs - deciding what a module is, where its code comes from, and how it is rewritten - plus lifecycle hooks and Vite-only server hooks. These are the ones you reach for most.

HookRuns duringWhat it does
resolveIdresolveMap an import string to a module id, or null to defer
loadloadReturn source for an id, or null to read from disk
transformloadRewrite a module's code, or null to leave it alone
configResolvedstartupRead the final config once it is settled
configureServerserveAdd dev-server middleware
transformIndexHtmlbothRewrite the HTML entry document

resolveId plus load: making a virtual module

Two hooks working as a pair let you serve a module with no file behind it. resolveId claims a bare specifier and returns an id; load recognizes that id and returns its source. The convention is to prefix the resolved id with a NUL byte (\0, which tools print as \u0000) so Vite and other plugins know it is synthetic and must never be read from disk.

const VIRTUAL = 'virtual:build-info';

function buildInfoPlugin(version) {
  const resolved = '\0' + VIRTUAL;   // NUL byte marks it as not-a-file
  return {
    name: 'build-info',
    resolveId(id) { return id === VIRTUAL ? resolved : null; },
    load(id) {
      if (id === resolved) return 'export const version = ' + JSON.stringify(version);
      return null;
    },
  };
}

Feed it the virtual specifier and a normal path, and watch which hooks claim which id:

Output:

resolveId("virtual:build-info") -> "\u0000virtual:build-info"
resolveId("./math.js") -> null
load("\u0000virtual:build-info") -> "export const version = \"1.4.0\""
load("./math.js") -> null

The virtual id resolves with its NUL marker and load supplies the generated source for exactly that id. Both hooks return null for ./math.js, so Vite resolves and reads the real file itself.

transform and the discipline of returning null

transform is where most plugins live. It receives a module's code and id and returns either new code or null. Returning null, rather than the unchanged string, matters: it tells the pipeline nothing changed, so Vite can skip reprocessing and keep the existing sourcemap. A module flows through every transform in pipeline order, each free to rewrite it or pass.

function makeTransforms() {
  return [
    { name: 'strip-debug', fn: (code, id) =>
        id.endsWith('.js') && code.includes('__DEBUG__')
          ? code.replace(/__DEBUG__/g, 'false') : null },
    { name: 'add-banner',  fn: (code) => '/* built */\n' + code },
    { name: 'css-scope',   fn: (code, id) =>
        id.endsWith('.css') ? code + ' /* scoped */' : null },
  ];
}

function runTransforms(transforms, code, id) {
  const touched = [];
  for (const t of transforms) {
    const out = t.fn(code, id);
    if (out !== null) { code = out; touched.push(t.name); }
  }
  return { code, touched };
}

const r = runTransforms(makeTransforms(), 'const on = __DEBUG__;\n', 'app.js');
console.log('touched by: ' + r.touched.join(', '));
console.log('result:');
process.stdout.write(r.code);

Output:

touched by: strip-debug, add-banner
result:
/* built */
const on = false;

For app.js, strip-debug and add-banner both fire while css-scope returns null and steps aside, so the module carries only the changes that actually applied.

enforce, apply, and knowing when not to write one

enforce places you in the pre, middle, or post group; apply restricts you to 'build' or 'serve'. A bundle-size reporter is apply: 'build'; a mock-API middleware added through configureServer is apply: 'serve'. Before writing anything, check whether Vite already does the job: asset imports, CSS Modules, preprocessors, TypeScript transpilation, JSON, and glob imports are all built in. Every plugin you add is code in your critical build path and one more version to keep current.


Real World Example: A Scoped-CSS Plugin That Churns Class Names

A team writes a small plugin to give every stylesheet a unique class prefix so component styles never collide. Each .css module that passes through transform gets a prefix - .p1__, .p2__, and so on. It works perfectly in the first vite build, so it ships.

function scopedCssStateful() {
  let n = 0;   // counter lives on the plugin instance
  return {
    name: 'scoped-css-stateful',
    transform(code, id) {
      if (!id.endsWith('.css')) return null;
      n += 1;
      return { code: '.p' + n + '__ ' + code };
    },
  };
}

The dev server is long-lived. One plugin instance handles the first build and then every hot rebuild after it, and n is never reset. The fix derives the prefix from the module id, so the same file always lands on the same name:

function scopedCssStateless() {
  return {
    name: 'scoped-css-stateless',
    transform(code, id) {
      if (!id.endsWith('.css')) return null;
      const h = crypto.createHash('sha256').update(id).digest('hex').slice(0, 4);
      return { code: '.p' + h + '__ ' + code };
    },
  };
}

Run each version across two builds, the second standing in for a hot rebuild on the same server:

Output:

SHIPPED (module-scoped counter):
  build 1 a.css -> .p1__ a{}
  build 1 b.css -> .p2__ b{}
  build 2 a.css -> .p3__ a{}
  build 2 b.css -> .p4__ b{}
  a.css prefix stable across rebuilds: false

FIXED (prefix derived from id):
  build 1 a.css -> .p96a7__ a{}
  build 2 a.css -> .p96a7__ a{}
  a.css prefix stable across rebuilds: true

The flaw is not the idea of prefixing; it is that transform is not a pure function of its inputs. The plugin carries mutable state - let n - on an instance that outlives a single build, so in a persistent dev server the counter climbs across rebuilds and the same source yields a different class name each time.

Downstream, every generated name churns on each edit: caches miss, any rule or markup that referenced .p2__ breaks, and the "unique prefix" guarantee quietly rots the longer the server runs. It hides in testing because a one-shot vite build from a cold process runs each module exactly once, so n looks perfectly stable.

The durable fix is the stateless version: derive the prefix from the module id, or from its content, so identical input always produces identical output - exactly the contract Rollup and Vite assume every transform honors. Any state a plugin truly needs should hang off the id or the content, never a variable that survives from one build to the next.


Common Mistakes

  1. Relying on array order instead of enforce. Vite sorts plugins into pre, middle, and post groups, and your array position only matters within a group. If a hook must run before core processing, set enforce: 'pre' rather than moving it up the list.
  1. Returning the unchanged string from transform instead of null. Handing back code untouched tells Vite the module changed, discarding the chance to skip work and preserve the sourcemap; return null when you did nothing.
  1. Forgetting the \0 prefix on a virtual module id. Without it, Vite's resolver and other plugins treat the synthetic id as a real path, try to read it from disk, and either fail or let an unrelated plugin claim it.
  1. Running a regex over every module. Skipping the early id filter means transform executes on every file, including node_modules; filter by extension or path first, then do the expensive work.
  1. Dropping the sourcemap with map: null in a shipping plugin. It is fine in a sketch, but returning map: null after rewriting code makes every downstream stack trace point at the wrong line; return a real map.
  1. Holding mutable state across the build. A module-scoped counter or cache survives rebuilds in the long-lived dev server, so transforms stop being pure and their output drifts; derive results from the input instead.
  1. Setting apply backwards. A dev-only mock middleware marked apply: 'build', or a bundle report marked apply: 'serve', simply never runs; match apply to the pipeline the plugin actually needs.
  1. Writing a plugin for something Vite already does. Asset imports, CSS Modules, preprocessors, JSON, glob imports, and TypeScript transpilation are built in; a hand-rolled version is dead weight and a maintenance burden.
  1. Omitting name. With no name, Vite's errors, warnings, and profiling cannot tell you which plugin misbehaved, turning a one-line fix into a hunt.

Best Practices

  • Filter by id before doing any work. Bail out with null for the extensions and paths you do not handle, so the pipeline stays fast and your logic only sees the modules it means to touch.
  • Keep every hook a pure function of its inputs. Given the same code and id, return the same result; push any shared state into the id or the content, never a variable that outlives a build.
  • Return null to mean "no change." It is the pipeline's signal to skip you and keep existing maps; reserve a returned value for when you genuinely rewrote something.
  • Prefix virtual module ids with \0. The NUL marker keeps synthetic ids out of filesystem resolution and signals to every other plugin that there is no file behind them.
  • Set enforce deliberately, not by trial. Decide whether you must act before core plugins, after them, or in the middle, and note why; it is the field people forget when a hook runs too late.
  • Scope with apply when a plugin belongs to one pipeline. Mark build-only tools apply: 'build' and dev-only middleware apply: 'serve' so they never fire in the wrong context.
  • Supply a real sourcemap whenever you rewrite code. An accurate map keeps stack traces and breakpoints aligned with the author's source - the difference between a debuggable build and a mysterious one.
  • Check the built-ins before adding a plugin. Confirm Vite does not already cover the need; every dependency in your build path is code to trust, audit, and upgrade.

Practice Exercises

  1. Trace the order. Given four plugins declared as [a (post), b, c (pre), d (pre)], write the exact order their transform hooks run, then state the rule that breaks ties inside the pre group.
  1. Build a virtual module. Write a plugin that makes import { version } from 'virtual:app-version' work, reading the version from a value passed to the plugin factory. Show both hooks and explain why the resolved id must start with \0.
  1. Find the state bug. You inherit a transform plugin that appends an incrementing comment /* module N */ to each file. Explain what goes wrong once the dev server has run through several edits, then rewrite it so the output is stable.
  1. Decide build or serve. You want a plugin that injects a fake /api responder during development only. Which hook adds the middleware, which apply value do you set, and what happens if you omit apply?