> [!IMPORTANT]
> The plugin has been adapted for `vite@7.x` and above versions. It will now automatically choose `esbuild`/`rolldown` to compile mock files based on the `vite` version.
## Features
- ⚡️ Lightweight, Flexible, Fast.
- 🧲 Not injection-based, non-intrusive to client code.
- 💡 Pure ESModule.
- 🦾 Typescript.
- 🔥 HMR
- 🏷 Support `.[cm]?js` / `.ts` / `.json` / `.json5`.
- 📦 Auto import mock file.
- 🎨 Support any lib, like `mockjs`, or do not use it.
- 📥 Path rule matching, request parameter matching.
- ⚙️ Support Enabled/Disabled any one of the API mock.
- 📀 Supports response body content type such as `text/json/buffer/stream`.
- ⚖️ Use `server.proxy`
- 🍕 Support `viteConfig.define` and `env` in the mock file.
- ⚓️ Support `viteConfig.resolve.alias` in the mock file.
- 🌈 Support `vite preview` mode.
- 📤 Support `multipart` content-type, mock upload file.
- 📥 Support mock download file.
- ⚜️ Support `WebSocket Mock` and `Server-Sent Events Mock`
- 📝 Support **recording** and **replay requests**
- 🗂 Support building small independent deployable mock services.
## Documentation
See the [documentation](https://vite-plugin-mock-dev-server.netlify.app/) for more details.
[](https://app.netlify.com/sites/vite-plugin-mock-dev-server/deploys)
> [!IMPORTANT]
> The plugin no longer supports `CommonJS` imports. Please use `ESModule` to import the plugin.
----
> [!IMPORTANT]
> The current document is for the `v2` version of the plugin. If you are using the `v1` version, please refer to the [Migration Guide](https://vite-plugin-mock-dev-server.netlify.app/guide/migrate-v2).
## Install
``` sh
# npm
npm i -D vite-plugin-mock-dev-server
# yarn
yarn add vite-plugin-mock-dev-server
# pnpm
pnpm add -D vite-plugin-mock-dev-server
```
## Usage
`vite.config.ts`
``` ts
import { defineConfig } from 'vite'
import { mockDevServerPlugin } from 'vite-plugin-mock-dev-server'
export default defineConfig({
plugins: [
mockDevServerPlugin(/* plugin options */),
],
// The fields defined here can also be used in mock.
define: {},
server: {
// plugin will read `server.proxy`
proxy: {
'^/api': { target: 'http://example.com' }
}
}
})
```
The plugin will read the configuration of `server.proxy` or `options.prefix`, and enable mock matching for matched URLs.
The plugin will also read the `define` configuration, which supports direct use in mock files.
## Edit Mock File
By default, write mock data in the `mock` directory of your project's root directory:
`mock/**/*.mock.ts` :
``` ts
import { defineMock } from 'vite-plugin-mock-dev-server'
export default defineMock({
url: '/api/user/:id',
body: { a: 1, b: 2 }
})
```
## Methods
### mockDevServerPlugin(pluginOptions)
vite plugin
`vite.config.ts`
``` ts
import { defineConfig } from 'vite'
import { mockDevServerPlugin } from 'vite-plugin-mock-dev-server'
export default defineConfig({
plugins: [
mockDevServerPlugin({ /* plugin options */ }),
]
})
```
### defineMock(mockOptions)
Mock Options Type Helper
``` ts
import { defineMock } from 'vite-plugin-mock-dev-server'
export default defineMock({
url: '/api/test',
body: {}
})
```
### createDefineMock(transformer)
Return a custom defineMock function to support preprocessing of mock config.
``` ts
import path from 'node:path'
import { createDefineMock } from 'vite-plugin-mock-dev-server'
// Preprocessed mock url
const defineAPIMock = createDefineMock((mock) => {
mock.url = path.join('/api', mock.url)
})
export default defineApiMock({
url: '/test' // Complete as '/api/test'
})
```
### createSSEStream(req, res)
Create a `Server-sent events` write stream to support mocking `EventSource`.
``` ts
import { createSSEStream, defineMock } from 'vite-plugin-mock-dev-server'
export default defineMock({
url: '/api/sse',
response: (req, res) => {
const sse = createSSEStream(req, res)
sse.write({ event: 'message', data: { message: 'hello world' } })
sse.end()
}
})
```
## Plugin Options
### enabled
- **Type:** `boolean`
- **Default:** `true`
- **Details:**
Whether to enable mock server, if set to `false`, the plugin will not work.
### prefix
- **Type:** `string | string[]`
- **Default:** `[]`
- **Details:**
Configure custom matching rules for the mock server. Any request path starting with the value of `prefix` will be proxied to the corresponding target. If the `prefix` value starts with ^, it will be recognized as a RegExp.
> In general, `server.proxy` is sufficient to meet the needs. Adding this item is for compatibility with certain scenarios.
### wsPrefix
- **Type:** `string | string[]`
- **Default:** `[]`
- **Details:**
Configure the matching rules for the WebSocket service. Any request path starting with the value of `wsPrefix` and using the `ws/wss` protocol will be proxied to the corresponding target.
If the value of `wsPrefix` starts with `^`, it will be recognized as a RegExp.
> Different from using `viteConfig.server.proxy` by default for http mock, `websocket mock` does not use the ws-related configuration in `viteConfig.server.proxy`. Also, rules configured in `wsPrefix` cannot be configured simultaneously in `viteConfig.server.proxy`, as it will cause conflicts when starting the vite server because multiple instances of WebSocketServer cannot be implemented for the same request.
> This conflict is neither a problem with Vite nor with the plugin; it belongs to a reasonable error type. When switching between WebSocket Mock and WebSocket Proxy, please pay attention to avoid duplicate configurations that may cause conflicts.
### cwd
- **Type:** `string`
- **Default:** `process.cwd()`
- **Details:**
Configure the matching context for `include` and `exclude`.
### dir
- **Type:** `string`
- **Default:** `'mock'`
- **Details:**
Configure the directory to read mock files.
### include
- **Type:** `string | string[]`
- **Default:** `['**/*.mock.{js,ts,cjs,mjs,json,json5}']`
- **Details:**
Configure to read mock files, which can be a directory, glob, or an array.
### exclude
- **Type:** `string | string[]`
- **Default:** `['**/node_modules/**']`
- **Details:**
When reading mock files for configuration, the files that need to be excluded can be a directory, glob, or array.
### reload
- **Type:** `boolean`
- **Default:** `false`
- **Details:**
When the mock resource is hot updated, only the data content is updated, but the page is not refreshed by default. If you want to refresh the page every time you modify the mock file, you can open this option.
### cors
- **Type:** `boolean | CorsOptions`
- **Default:** `true`
- **Details:**
Enable by default.
Configure to `cors`, see [cors](https://github.com/expressjs/cors#configuration-options)
### log
- **Type:** `boolean | 'info' | 'warn' | 'error' | 'silent' | 'debug'`
- **Default:** `info`
- **Details:**
Enable log and configure log level.
### formidableOptions
- **Type:** `formidable.Options`
- **Details:**
Configure to `formidable`, see [formidable options](https://github.com/node-formidable/formidable#options)
example: Configure to file upload dir
``` ts
MockDevServerPlugin({
formidableOptions: {
uploadDir: path.join(process.cwd(), 'uploads'),
}
})
```
### cookiesOptions
- **Type:** `CookiesOptions`
- **Details:**
Configure to `cookies`, see [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options)
### bodyParserOptions
- **Type:** `BodyParserOptions`
- **Details:**
Configure to `co-body`, see [co-body](https://github.com/cojs/co-body#options)
### build
- **Type:** `boolean | ServerBuildOptions`
- **Default:** `false`
- **Details:**
The configuration needed to build a small, independently deployable mock service.
``` ts
interface ServerBuildOptions {
/**
* server port
* @default 8080
*/
serverPort?: number
/**
* build output dir
* @default 'mockServer'
*/
dist?: string
/**
* log level
* @default 'error'
*/
log?: LogLevel
}
```
### record
- **Type:** `false | RecordOptions`
- **Default:** `false`
- **Details:**
Whether to enable the request recording feature. Once enabled, the plugin will record all request data for subsequent request playback.
Based on `vite.server.proxy`, the plugin records request data proxied by `http-proxy`.
After receiving a response, the plugin will record the request data and response data to the specified directory.
```ts
interface RecordOptions {
/**
* Whether to enable the record feature
* - true: Enable, automatically record proxy responses
* - false: Disable (default)
* @default false
*/
enabled?: boolean
/**
* Filter requests to record
* - Function: Custom filter function, return true to record
* - Object: Include/exclude patterns with glob or path-to-regexp mode
* @example
* ```ts
* // Record all requests
* filter: (req) => true
* // Record requests using glob pattern
* filter: { mode: 'glob', include: '/api/**' }
* // Record requests using path-to-regexp pattern
* filter: { mode: 'path-to-regexp', include: '/api/:id' }
* ```
*/
filter?: ((req: RecordedReq) => boolean) | {
/**
* Include the request links that need to be recorded
*
* String: Glob pattern or path-to-regexp pattern
* (Use the mode option to set the mode, default is glob)
*/
include?: string | string[]
/**
* Exclude request links that do not need to be recorded
*
* String: Glob pattern or path-to-regexp pattern
* (Use the mode option to set the mode, default is glob)
*/
exclude?: string | string[]
/**
* Matching mode for include/exclude patterns
* - 'glob': Glob pattern matching (default)
* - 'path-to-regexp': Path-to-regexp pattern matching
*/
mode: 'glob' | 'path-to-regexp'
}
/**
* Directory to store recorded data
* Relative to project root
* @default 'mock/.recordings'
*/
dir?: string
/**
* Whether to overwrite existing recorded data
* - true: Overwrite old data for the same request (default)
* - false: Keep old data, do not record new data
* @default true
*/
overwrite?: boolean
/**
* Expiration time for recorded data in seconds
* - 0: Never expire (default)
* - Positive number: Expire after specified seconds
* @default 0
*/
expires?: number
/**
* Status codes to record
* - Empty array: Record all status codes (default)
* - Specify one or more status codes to filter
* @default []
*/
status?: number | number[]
/**
* Should a .gitignore be added to the recording directory
* - true: Add (default)
* - false: Do not add
* @default true
*/
gitignore?: boolean
}
```
### replay
- **Type:** `boolean`
- **Default:** `false`
- **Details:**
Whether to enable the request playback feature. Once enabled, the plugin will simulate responses based on the recorded request data.
### priority
- **Type:** `MockMatchPriority`
- **Details:**
Custom path matching rule priority。[read more](#custom-path-matching-priority)
## Mock Options
**http mock**
```ts
import { defineMock } from 'vite-plugin-mock-dev-server'
export default defineMock({
url: '/api/test',
body: { message: 'hello world' }
})
```
**websocket mock**
```ts
import { defineMock } from 'vite-plugin-mock-dev-server'
export default defineMock({
url: '/socket.io',
ws: true,
setup(wss) {
wss.on('connection', (ws, req) => {
console.log('connected')
})
}
})
```
### options.url
- **Type:** `string`
- **Details:**
The interface address that needs to be mocked, supported by [path-to-regexp](https://github.com/pillarjs/path-to-regexp) for path matching.
### options.enabled
- **Type:** `boolean`
- **Default:** `true`
- **Details:**
Whether to enable mock for this interface. In most scenarios, we only need to mock some interfaces instead of all requests that have been configured with mock.
Therefore, it is important to be able to configure whether to enable it or not.
### options.method
- **Type:** `Method | Method[]`
```ts
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH'
```
- **Default:** `['GET', 'POST']`
- **Details:**
The interface allows request methods
### options.type
- **Type:** `'text' | 'json' | 'buffer' | string`
- **Details:**
Response body data type. And also support types included in [mime-db](https://github.com/jshttp/mime-db).
When the response body returns a file and you are not sure which type to use,
you can pass the file name as the value. The plugin will internally search for matching
`content-type` based on the file name suffix.
### options.headers
- **Type:** `object | (request: MockRequest) => object | Promise