Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท Plugins

Virtual Modules and Custom HMR

Create virtual modules with resolveId and load, add dev-server middleware with configureServer, and send custom hot updates with handleHotUpdate and server.ws.

Some modules do not exist on disk. A build-time version string, a list of routes generated from your pages/ folder, or the contents of a config file turned into JavaScript are all easier to expose as an import than as a generated file you must remember to commit or ignore. Vite plugins solve this with virtual modules: an import name that the plugin resolves and loads itself.

In this lesson you will build a virtual module, learn the \0 convention, add a dev-server middleware with configureServer, and push a custom update to the browser. Real Vite code is read-only; the logic is demonstrated with runnable stand-ins.

Virtual modules in four lines

JavaScript
// vite-plugin-build-info.js (real Vite, read-only)
const virtualId = 'virtual:build-info';
const resolvedId = '\0' + virtualId;

export default function buildInfo() {
  return {
    name: 'build-info',
    resolveId(source) {
      if (source === virtualId) return resolvedId;
    },
    load(id) {
      if (id === resolvedId) {
        return `export const builtAt = ${JSON.stringify(new Date().toISOString())};
export const mode = ${JSON.stringify(process.env.NODE_ENV ?? 'development')};`;
      }
    },
  };
}

Application code then writes import { builtAt } from 'virtual:build-info';. The pieces:

  • The public name starts with virtual:, a convention that signals "not a real package".
  • resolveId claims the import and returns an internal id. The leading \0 is a Rollup convention: other plugins see it and skip the module, so nobody tries to read it from disk.
  • load returns the source code for that internal id. After that, the module is transformed and bundled like any other.

For TypeScript, declare the module so editors know it exists:

TypeScript
// env.d.ts
declare module 'virtual:build-info' {
  export const builtAt: string;
  export const mode: string;
}

Runnable stand-in

This stand-in resolves and loads virtual modules from a registry, and evaluates the generated code to prove it is valid JavaScript.

JS Stand-in: a virtual module

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

No output.

The file-name to route conversion is the same idea file-based routers use. Because it runs in load, adding a file to pages/ just needs the module invalidated (see below).

configureServer: middleware in dev

configureServer runs only in dev and gets the dev server object. The most common use is adding middleware before Vite's own, for example a fake API:

JavaScript
// real Vite, read-only
export default function mockApi() {
  return {
    name: 'mock-api',
    configureServer(server) {
      server.middlewares.use('/api/hello', (req, res) => {
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify({ message: 'Hello from the dev server' }));
      });
    },
  };
}

server.middlewares is a Connect instance, so the signature is (req, res, next) as in Express. If the function returns another function, that inner function runs after Vite's internal middlewares, which is the right place for a fallback handler such as serving an SPA's index.html for unknown routes.

JS Stand-in: a middleware chain

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

No output.

handleHotUpdate and custom events

When a watched file changes, Vite calls handleHotUpdate(ctx). The context has file, modules (affected modules in the graph), read() and server. A plugin can narrow the modules, or send a custom message through the WebSocket:

JavaScript
// real Vite, read-only
handleHotUpdate({ file, server }) {
  if (file.endsWith('.csv')) {
    server.ws.send({ type: 'custom', event: 'csv-changed', data: { file } });
    return []; // handled: do not run the default update
  }
}

In the browser, listen with the HMR API:

JavaScript
// client code (real Vite)
if (import.meta.hot) {
  import.meta.hot.on('csv-changed', (data) => {
    console.log('CSV changed:', data.file);
  });
}

For a virtual module that depends on files on disk, invalidate it when those files are added or removed, so the next request runs load again:

JavaScript
configureServer(server) {
  server.watcher.on('add', () => {
    const mod = server.moduleGraph.getModuleById('\0virtual:routes');
    if (mod) server.moduleGraph.invalidateModule(mod);
    server.ws.send({ type: 'full-reload' });
  });
}

Common mistakes

  • Forgetting the \0 prefix: other plugins then try to read a file called virtual:build-info and fail with a confusing error.
  • Returning the virtual id from load instead of the code.
  • Building a virtual module from files but never invalidating it, so new files do not show up until a restart.
  • Registering a middleware in a plugin that also runs in build; configureServer is dev-only, which is usually what you want.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a virtual module's resolved id start with \0?

    The null-character prefix is a Rollup convention: tools skip such ids, and only the owning plugin handles them.
  2. 2. Which hooks together create a virtual module?

    resolveId claims the import name and load returns its source.
  3. 3. When does configureServer run?

    configureServer receives the dev server instance, so it is dev-only.
  4. 4. What does returning an empty array from handleHotUpdate mean?

    handleHotUpdate returns the list of modules to update. An empty list cancels the default update.

Summary

  • Virtual modules use resolveId (claim a name, return a \0 id) and load (return code).
  • Declare types for virtual imports in a .d.ts file.
  • configureServer adds dev middleware and watchers; returning a function runs after Vite's middlewares.
  • handleHotUpdate customizes updates; server.ws.send and import.meta.hot.on carry custom events.
  • Invalidate virtual modules that depend on files on disk.

Next: Official and Community Plugins