vite-plugin-mock

raw JSON →
3.0.2 verified Mon Apr 27 auth: no javascript

A mock plugin for Vite that provides local mock data for development and testing. Current stable version is 3.0.2, with active development and releases. It integrates with Vite's dev server, supports hot module replacement (HMR) for mock files, and allows mocking API requests during development. Differentiated by its tight integration with Vite, TypeScript support, and use of mockjs for data generation. Requires Vite >=4.0.0, esbuild >=0.17, and mockjs >=1.1.0 as peer dependencies.

error Cannot find module 'mockjs'
cause Missing mockjs dependency.
fix
npm install mockjs --save-dev
error TypeError: viteMockServe is not a function
cause Attempting to import default export as named export.
fix
Use import { viteMockServe } from 'vite-plugin-mock' or import vitePluginMock from 'vite-plugin-mock'
error Vite plugin 'vite-plugin-mock' can only be used with Vite >=4.0.0
cause Running with an older version of Vite.
fix
Upgrade Vite to >=4.0.0
error Mock file not found: /path/to/mock
cause mockPath is misconfigured or directory does not exist.
fix
Check mockPath in viteMockServe config and ensure the directory exists.
breaking vite-plugin-mock v3 drops support for Vite <4 and Node <16.
fix Upgrade Vite to >=4.0.0 and Node to >=16.0.0.
deprecated The 'supportTs' option is deprecated and may be removed.
fix Remove 'supportTs' from config; TypeScript is automatically supported.
gotcha Mock files are resolved relative to the project root by default. Ensure 'mockPath' is correct.
fix Set 'mockPath' to the absolute or relative path to your mock directory.
breaking vite-plugin-mock v3 no longer exports default mock configuration; use named export.
fix Change 'import vitePluginMock from 'vite-plugin-mock'' to 'import { viteMockServe } from 'vite-plugin-mock''.
gotcha HMR may not work when mock files are outside the project root.
fix Place mock files inside the project root or use symlinks.
npm install vite-plugin-mock
yarn add vite-plugin-mock
pnpm add vite-plugin-mock

Configures vite-plugin-mock in vite.config.ts and creates a simple mock endpoint for /api/user.

// vite.config.ts
import { defineConfig } from 'vite';
import { viteMockServe } from 'vite-plugin-mock';

export default defineConfig({
  plugins: [
    viteMockServe({
      mockPath: 'mock',
      enable: true,
      watchFiles: true,
    }),
  ],
});

// mock/user.ts
import { MockMethod } from 'vite-plugin-mock';
export default [
  {
    url: '/api/user',
    method: 'get',
    response: () => ({
      code: 0,
      data: { id: 1, name: 'John' },
    }),
  },
] as MockMethod[];