Vite Plugin for API Mock Server

2.1.1 · active · verified Sun Apr 19

vite-plugin-mock-dev-server is a Vite plugin designed to provide a lightweight, flexible, and fast API mock development server. It is currently stable at version 2.1.1 and receives frequent updates, including new features and bug fixes. Key differentiators include its non-intrusive, non-injection-based approach to mocking, full TypeScript support, Hot Module Replacement (HMR) for mock files, and pure ES Module architecture since version 2.0.0. The plugin automatically imports mock files from designated directories (default `mock` folder) and supports various content types for responses (text, JSON, buffer, stream). It integrates seamlessly with Vite's `server.proxy` configuration and allows the use of `viteConfig.define` and environment variables within mock definitions. Advanced features like WebSocket mocking, request recording/replay, error simulation, and the ability to build small, independent deployable mock services further enhance its utility for front-end development workflows.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure `vite-plugin-mock-dev-server` in `vite.config.ts` and define mock API endpoints using `defineMock` within a mock file. It shows basic GET requests, path parameter handling, response delays, error simulation, and HMR persistence.

import { defineConfig } from 'vite';
import mockDevServerPlugin from 'vite-plugin-mock-dev-server';

export default defineConfig({
  plugins: [
    mockDevServerPlugin({
      // Optional: Specify mock files directory, relative to cwd.
      // dir: 'mocks',
      // Optional: Enable/disable the plugin entirely.
      enabled: process.env.NODE_ENV === 'development'
    }),
  ],
  // 'define' fields are accessible within mock files.
  define: {
    __APP_VERSION__: JSON.stringify('1.0.0'),
  },
  server: {
    proxy: {
      // The plugin reads `server.proxy` to determine which URLs to mock.
      // Requests matching '/api' will be handled by the mock server if enabled.
      '^/api': {
        target: 'http://localhost:3000', // Actual backend or a placeholder
        changeOrigin: true,
      },
    },
  },
});

// mock/users.mock.ts
import { defineMock } from 'vite-plugin-mock-dev-server';

export default defineMock([
  {
    url: '/api/users',
    method: 'GET',
    body: [
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' },
    ],
    delay: 500, // Simulate network latency
  },
  {
    url: '/api/users/:id',
    method: 'GET',
    body: ({ params }) => ({ id: Number(params.id), name: `User ${params.id}` }),
    // Persist mock data on HMR to avoid data loss during development
    persistOnHMR: true
  },
  {
    url: '/api/error',
    method: 'GET',
    status: 500,
    body: { message: 'Internal Server Error' },
  }
]);

view raw JSON →