{"id":12371,"library":"vite-plugin-mock-dev-server","title":"Vite Plugin for API Mock Server","description":"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.","status":"active","version":"2.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/pengzhanbo/vite-plugin-mock-dev-server","tags":["javascript","vite","plugin","vite-plugin","mock","mock-server","development","typescript"],"install":[{"cmd":"npm install vite-plugin-mock-dev-server","lang":"bash","label":"npm"},{"cmd":"yarn add vite-plugin-mock-dev-server","lang":"bash","label":"yarn"},{"cmd":"pnpm add vite-plugin-mock-dev-server","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core peer dependency for a Vite plugin, required for its functionality.","package":"vite","optional":false},{"reason":"Peer dependency for efficient bundling and transformation, especially with TypeScript.","package":"esbuild","optional":false},{"reason":"Peer dependency for advanced bundling scenarios.","package":"rolldown","optional":false},{"reason":"Peer dependency, likely for compression/decompression utilities within the mock server.","package":"zstd-codec","optional":false}],"imports":[{"note":"The package is pure ESM since v2.0.0. Use `import` syntax. Direct default import is common for Vite plugins.","wrong":"const mockDevServerPlugin = require('vite-plugin-mock-dev-server')","symbol":"mockDevServerPlugin","correct":"import mockDevServerPlugin from 'vite-plugin-mock-dev-server'"},{"note":"`defineMock` is a named export used for defining individual mock data objects within mock files.","wrong":"import defineMock from 'vite-plugin-mock-dev-server'","symbol":"defineMock","correct":"import { defineMock } from 'vite-plugin-mock-dev-server'"},{"note":"Import types separately for type-checking when configuring the plugin.","symbol":"mockDevServerPluginOptions","correct":"import type { MockDevServerPluginOptions } from 'vite-plugin-mock-dev-server'"}],"quickstart":{"code":"import { defineConfig } from 'vite';\nimport mockDevServerPlugin from 'vite-plugin-mock-dev-server';\n\nexport default defineConfig({\n  plugins: [\n    mockDevServerPlugin({\n      // Optional: Specify mock files directory, relative to cwd.\n      // dir: 'mocks',\n      // Optional: Enable/disable the plugin entirely.\n      enabled: process.env.NODE_ENV === 'development'\n    }),\n  ],\n  // 'define' fields are accessible within mock files.\n  define: {\n    __APP_VERSION__: JSON.stringify('1.0.0'),\n  },\n  server: {\n    proxy: {\n      // The plugin reads `server.proxy` to determine which URLs to mock.\n      // Requests matching '/api' will be handled by the mock server if enabled.\n      '^/api': {\n        target: 'http://localhost:3000', // Actual backend or a placeholder\n        changeOrigin: true,\n      },\n    },\n  },\n});\n\n// mock/users.mock.ts\nimport { defineMock } from 'vite-plugin-mock-dev-server';\n\nexport default defineMock([\n  {\n    url: '/api/users',\n    method: 'GET',\n    body: [\n      { id: 1, name: 'Alice' },\n      { id: 2, name: 'Bob' },\n    ],\n    delay: 500, // Simulate network latency\n  },\n  {\n    url: '/api/users/:id',\n    method: 'GET',\n    body: ({ params }) => ({ id: Number(params.id), name: `User ${params.id}` }),\n    // Persist mock data on HMR to avoid data loss during development\n    persistOnHMR: true\n  },\n  {\n    url: '/api/error',\n    method: 'GET',\n    status: 500,\n    body: { message: 'Internal Server Error' },\n  }\n]);","lang":"typescript","description":"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."},"warnings":[{"fix":"Migrate all imports from `require('vite-plugin-mock-dev-server')` to `import mockDevServerPlugin from 'vite-plugin-mock-dev-server'`. Ensure your Vite configuration file (`vite.config.ts` or `.js`) is configured for ESM.","message":"Version 2.0.0 introduced pure ES Module (ESM) support. This means CommonJS `require()` syntax is no longer directly supported for importing the plugin or its utilities. Projects must use `import` statements.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Review existing mock `url` patterns, especially those with advanced regex or segment definitions, and update them according to `path-to-regexp` v8 specifications. Test all mock routes thoroughly.","message":"The underlying `path-to-regexp` library was upgraded from v6 to v8 in version 2.0.0. This might introduce breaking changes in how path patterns are parsed, especially concerning special characters or complex regular expressions. Refer to the `path-to-regexp` official documentation for specific migration details.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Explicitly set the `dir` option in the plugin configuration if your mock files are not in the default `mock` directory (e.g., `mockDevServerPlugin({ dir: 'src/mocks' })`). Verify that your `include` and `exclude` patterns, if used, correctly resolve against the new base directory.","message":"Version 2.0.0 added a new `dir` configuration option to specify the directory for mock files, relative to `cwd`. While it defaults to `mock`, if you previously relied on a different implicit behavior or custom configuration, this might affect mock file discovery.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Ensure your development environment uses Node.js version 20 or greater, or 22 or greater. Update Node.js if necessary (e.g., using `nvm install 20 && nvm use 20`).","message":"The plugin requires Node.js version 20 or higher, or version 22 or higher, as specified in its `engines` field. Using older Node.js versions will prevent the plugin from installing or running correctly.","severity":"gotcha","affected_versions":"all"},{"fix":"Add or verify `server.proxy` in your `vite.config.ts` (e.g., `server: { proxy: { '^/api': { target: 'http://localhost:3000' } } }`). Ensure the proxy prefix matches the `url` patterns defined in your mock files.","message":"For the mock server to intercept requests, you must configure `server.proxy` in your `vite.config.ts` with a target matching your mock URLs. The plugin reads this configuration to enable mock matching. If `server.proxy` is missing or misconfigured, mocks will not be active.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure your `vite.config.js` uses ES Module syntax (e.g., `import mockDevServerPlugin from 'vite-plugin-mock-dev-server'`) and potentially change the file extension to `.mjs` or ensure your Node.js environment correctly handles ESM.","cause":"Attempting to `require` the plugin in a CommonJS-style Vite configuration file when the package is ESM-only.","error":"Error: [plugin:vite-plugin-mock-dev-server] Failed to load config from ...vite.config.js: vite-plugin-mock-dev-server is not a function"},{"fix":"Ensure every mock file exports its definitions using `export default defineMock({...})` or `export default defineMock([...])`.","cause":"A mock file (e.g., `mock/my-api.mock.ts`) is missing the `export default defineMock(...)` structure.","error":"Error: mock file does not contain a default export or 'defineMock' call."},{"fix":"Verify that `server.proxy` in `vite.config.ts` includes a rule that matches `/api/my-endpoint` (e.g., `'^/api': { target: '...' }`). Also, check the `url` property in your `defineMock` call to ensure it precisely matches the requested path, including any path parameters.","cause":"The mock API endpoint is not being intercepted by the mock server, often due to misconfigured `server.proxy` or incorrect `url` matching in the mock definition.","error":"GET http://localhost:5173/api/my-endpoint 404 (Not Found)"}],"ecosystem":"npm"}