Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Plugins

Writing a Transform Plugin

Write a real Vite plugin step by step: filter files, transform code, keep source maps honest, add options, and test the logic as a plain function.

Reading about hooks is one thing; shipping a plugin is another. In this lesson you build a small but realistic plugin: one that turns a custom .csv file into a JavaScript module so you can write import rows from './people.csv'. Along the way you learn the habits that separate a robust plugin from a fragile one: filtering by file type, returning a source map, reporting errors with context, and keeping the core logic in a plain function you can test.

You should know the hook model from Anatomy of a Vite Plugin. The plugin below is real Vite code and read-only; the logic inside is tested in a runnable block.

The goal

Given a file people.csv:

Text
name,age
Ada,36
Linus,54

we want this to work in application code:

JavaScript
import people from './people.csv';
console.log(people[0].name); // "Ada"

The browser cannot import CSV, so the plugin must convert the file into JavaScript at the transform stage. A module that default-exports an array of objects is easy to generate.

The real plugin

JavaScript
// vite-plugin-csv.js (real Vite, read-only)
import { createFilter } from 'vite';
import { csvToObjects } from './csv-to-objects.js';

export default function csv(options = {}) {
  const filter = createFilter(options.include ?? '**/*.csv', options.exclude);

  return {
    name: 'vite-plugin-csv',

    transform(code, id) {
      if (!filter(id)) return null;

      let rows;
      try {
        rows = csvToObjects(code);
      } catch (error) {
        this.error(`Invalid CSV in ${id}: ${error.message}`);
      }

      return {
        code: `export default ${JSON.stringify(rows)};`,
        map: null,
      };
    },
  };
}

Then register it:

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

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

Four details are worth studying.

Factory with options. csv() returns the plugin object, so callers can write csv({ include: 'data/**/*.csv' }). Always give options sensible defaults.

createFilter. It builds a function from glob patterns and handles the awkward cases: query strings are stripped and virtual ids starting with \0 are ignored. Prefer it to id.endsWith('.csv').

this.error. It aborts with a message that includes the plugin name, and Vite's dev overlay displays it in the browser. A plain throw works too, but you lose the formatting.

map: null. This tells Vite "the output is a total rewrite, there is no meaningful source map". If you only change a few lines, return a real map (libraries such as magic-string generate them) so breakpoints in DevTools still match your source. Returning code without a map for a partial edit silently breaks debugging.

Test the logic as a plain function

The conversion code does not depend on Vite at all, so you can run and test it anywhere. This is the biggest practical tip for plugin authors: keep the transformation in a pure function and make the plugin a thin wrapper.

JS CSV to objects (the plugin's core logic)

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

No output.

The numbers were converted (36, not "36") and a malformed line produced a clear error that names the line. In the real plugin that message would appear in Vite's error overlay.

Simulating the transform hook

You can also test the hook itself with a tiny fake context, so the filter and error path are covered.

JS Test the hook with a fake context

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

No output.

Note that the id /src/data.csv?v=5 still matched, and /src/app.js returned null (not ours). These two cases are the ones most often forgotten.

Dev vs build and HMR

A transform plugin runs in both dev and build with no extra work. If your plugin reads a file that is not part of the module graph (for example a config file you parse inside buildStart), call this.addWatchFile(path) so Vite reloads when it changes. Editing a .csv that is imported normally already triggers a hot update, because the module graph knows about it.

Publishing tips

  • Name it vite-plugin-* and add vite-plugin to package.json keywords.
  • Declare vite as a peer dependency, not a dependency.
  • If it also works in Rollup, say so and name it rollup-plugin-*.
  • Document enforce or apply requirements in the README.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use createFilter instead of id.endsWith('.csv')?

    createFilter accepts include/exclude globs and copes with ids such as file.csv?v=1 and virtual modules.
  2. 2. What does returning { code, map: null } from transform mean?

    map: null says the output has no meaningful source map, which is fine for a full rewrite.
  3. 3. How should you structure a plugin so it is easy to test?

    A pure function can be unit-tested without starting Vite; the plugin object only connects it to the hook.
  4. 4. Which call reports an error with the plugin name attached?

    this.error() aborts the hook and Vite displays the message with the plugin and module id.

Summary

  • A transform plugin is a factory returning { name, transform }.
  • Filter with createFilter, return null for files that are not yours.
  • Use this.error, and return a source map unless the output is a total rewrite.
  • Keep the core logic a pure function so it is testable without Vite.
  • Use this.addWatchFile for files outside the module graph.

Next: Virtual Modules and Custom HMR