{"id":13417432,"url":"https://github.com/pengzhanbo/vite-plugin-mock-dev-server","last_synced_at":"2025-05-15T16:04:43.135Z","repository":{"id":62304820,"uuid":"559478980","full_name":"pengzhanbo/vite-plugin-mock-dev-server","owner":"pengzhanbo","description":"🚀mock-dev-server is injected into the vite development environment to simulate requests and data responses.在vite 开发环境中注入 mock-dev-server, 模拟请求和数据响应","archived":false,"fork":false,"pushed_at":"2025-04-10T04:11:11.000Z","size":1388,"stargazers_count":206,"open_issues_count":3,"forks_count":16,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-05-08T09:06:12.616Z","etag":null,"topics":["fakerjs","graphql","mock","mock-server","mockjs","proxy","typescript","vite","vite-plugin","vitejs","websocket"],"latest_commit_sha":null,"homepage":"https://vite-plugin-mock-dev-server.netlify.app","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pengzhanbo.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-10-30T08:39:56.000Z","updated_at":"2025-05-03T07:36:54.000Z","dependencies_parsed_at":"2024-01-25T10:35:17.024Z","dependency_job_id":"a0d91321-c6f8-4c24-aaec-8d4e3ab34329","html_url":"https://github.com/pengzhanbo/vite-plugin-mock-dev-server","commit_stats":{"total_commits":496,"total_committers":8,"mean_commits":62.0,"dds":0.08266129032258063,"last_synced_commit":"9345cd006db538f64a8374ea91b78aae0e74379e"},"previous_names":[],"tags_count":87,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pengzhanbo%2Fvite-plugin-mock-dev-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pengzhanbo%2Fvite-plugin-mock-dev-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pengzhanbo%2Fvite-plugin-mock-dev-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pengzhanbo%2Fvite-plugin-mock-dev-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pengzhanbo","download_url":"https://codeload.github.com/pengzhanbo/vite-plugin-mock-dev-server/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253534846,"owners_count":21923552,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fakerjs","graphql","mock","mock-server","mockjs","proxy","typescript","vite","vite-plugin","vitejs","websocket"],"created_at":"2024-07-30T22:00:37.126Z","updated_at":"2025-05-15T16:04:43.098Z","avatar_url":"https://github.com/pengzhanbo.png","language":"TypeScript","funding_links":[],"categories":["Plugins","TypeScript"],"sub_categories":["Framework-agnostic Plugins"],"readme":"# vite-plugin-mock-dev-server\n\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cp align=\"center\"\u003e\n \u003cb\u003eVite Plugin for API mock dev server.\u003c/b\u003e\n\u003c/p\u003e\n\n\u003cbr\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://www.npmjs.com/package/vite-plugin-mock-dev-server\"\u003e\u003cimg alt=\"npm\" src=\"https://img.shields.io/npm/v/vite-plugin-mock-dev-server?style=flat-square\"\u003e\u003c/a\u003e\n  \u003cimg alt=\"node-current\" src=\"https://img.shields.io/node/v/vite-plugin-mock-dev-server?style=flat-square\"\u003e\n  \u003cimg alt=\"npm peer dependency version\" src=\"https://img.shields.io/npm/dependency-version/vite-plugin-mock-dev-server/peer/vite?style=flat-square\"\u003e\n  \u003cimg alt=\"npm\" src=\"https://img.shields.io/npm/dm/vite-plugin-mock-dev-server?style=flat-square\"\u003e\n  \u003cbr\u003e\n  \u003cimg alt=\"GitHub Workflow Status\" src=\"https://img.shields.io/github/actions/workflow/status/pengzhanbo/vite-plugin-mock-dev-server/lint.yml?style=flat-square\"\u003e\n  \u003ca href=\"https://app.fossa.com/projects/git%2Bgithub.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server?ref=badge_shield\"\u003e\u003cimg alt=\"fossa status\" src=\"https://app.fossa.com/api/projects/git%2Bgithub.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server.svg?type=shield\"\u003e\u003c/a\u003e\n\u003c/p\u003e\n\u003cbr\u003e\n\u003cp align=\"center\"\u003e\n  \u003cspan\u003eEnglish\u003c/span\u003e | \u003ca href=\"/README.zh-CN.md\"\u003e简体中文\u003c/a\u003e\n\u003c/p\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\n## Features\n\n- ⚡️ Lightweight, Flexible, Fast.\n- 🧲 Not injection-based, non-intrusive to client code.\n- 💡 ESModule/commonjs.\n- 🦾 Typescript.\n- 🔥 HMR\n- 🏷 Support `.[cm]?js` / `.ts` / `.json` / `.json5`.\n- 📦 Auto import mock file.\n- 🎨 Support any lib, like `mockjs`, or do not use it.\n- 📥 Path rule matching, request parameter matching.\n- ⚙️ Support Enabled/Disabled any one of the API mock.\n- 📀 Supports response body content type such as `text/json/buffer/stream`.\n- ⚖️ Use `server.proxy`\n- 🍕 Support `viteConfig.define` and `env` in the mock file.\n- ⚓️ Support `viteConfig.resolve.alias` in the mock file.\n- 🌈 Support `vite preview` mode.\n- 📤 Support `multipart` content-type, mock upload file.\n- 📥 Support mock download file.\n- ⚜️ Support `WebSocket Mock` and `Server-Sent Events Mock`\n- 🗂 Support building small independent deployable mock services.\n\n## Documentation\n\nSee the [documentation](https://vite-plugin-mock-dev-server.netlify.app/en/) for more details.\n\n[![Netlify Status](https://api.netlify.com/api/v1/badges/9ccda610-2c6a-4cd0-aeaa-a8932f2b477c/deploy-status)](https://app.netlify.com/sites/vite-plugin-mock-dev-server/deploys)\n\n## Install\n\n``` sh\n# npm\nnpm i -D vite-plugin-mock-dev-server\n# yarn\nyarn add vite-plugin-mock-dev-server\n# pnpm\npnpm add -D vite-plugin-mock-dev-server\n```\n\n## Usage\n\n`vite.config.ts`\n\n``` ts\nimport { defineConfig } from 'vite'\nimport { mockDevServerPlugin } from 'vite-plugin-mock-dev-server'\n\nexport default defineConfig({\n  plugins: [\n    mockDevServerPlugin(/* plugin options */),\n  ],\n  // The fields defined here can also be used in mock.\n  define: {},\n  server: {\n    // plugin will read `server.proxy`\n    proxy: {\n      '^/api': { target: 'http://example.com' }\n    }\n  }\n})\n```\n\nThe plugin will read the configuration of `server.proxy` or `options.prefix`, and enable mock matching for matched URLs.\n\nThe plugin will also read the `define` configuration, which supports direct use in mock files.\n\n## Edit Mock File\n\nBy default, write mock data in the `mock` directory of your project's root directory:\n\n`mock/**/*.mock.ts` :\n\n``` ts\nimport { defineMock } from 'vite-plugin-mock-dev-server'\n\nexport default defineMock({\n  url: '/api/test',\n  body: { a: 1, b: 2 }\n})\n```\n\n## Methods\n\n### mockDevServerPlugin(pluginOptions)\n\nvite plugin\n\n`vite.config.ts`\n\n``` ts\nimport { defineConfig } from 'vite'\nimport { mockDevServerPlugin } from 'vite-plugin-mock-dev-server'\n\nexport default defineConfig({\n  plugins: [\n    mockDevServerPlugin({ /* plugin options */ }),\n  ]\n})\n```\n\n### defineMock(mockOptions)\n\nMock Options Type Helper\n\n``` ts\nimport { defineMock } from 'vite-plugin-mock-dev-server'\n\nexport default defineMock({\n  url: '/api/test',\n  body: {}\n})\n```\n\n### createDefineMock(transformer)\n\nReturn a custom defineMock function to support preprocessing of mock config.\n\n``` ts\nimport path from 'node:path'\nimport { createDefineMock } from 'vite-plugin-mock-dev-server'\n\n// Preprocessed mock url\nconst defineAPIMock = createDefineMock((mock) =\u003e {\n  mock.url = path.join('/api', mock.url)\n})\n\nexport default defineApiMock({\n  url: '/test' // Complete as '/api/test'\n})\n```\n\n### createSSEStream(req, res)\n\nCreate a `Server-sent events` write stream to support mocking `EventSource`.\n\n``` ts\nimport { createSSEStream, defineMock } from 'vite-plugin-mock-dev-server'\n\nexport default defineMock({\n  url: '/api/sse',\n  response: (req, res) =\u003e {\n    const sse = createSSEStream(req, res)\n    sse.write({ event: 'message', data: { message: 'hello world' } })\n    sse.end()\n  }\n})\n```\n\n## Plugin Options\n\n### prefix\n\n- **Type:** `string | string[]`\n- **Default:** `[]`\n- **Details:**\n\n  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.\n\n  \u003e In general, `server.proxy` is sufficient to meet the needs. Adding this item is for compatibility with certain scenarios.\n\n### wsPrefix\n\n- **Type:** `string | string[]`\n- **Default:** `[]`\n- **Details:**\n\n  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.\n\n  If the value of `wsPrefix` starts with `^`, it will be recognized as a RegExp.\n\n  \u003e 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.\n  \u003e 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.\n\n### cwd\n\n- **Type:** `string`\n- **Default:** `process.cwd()`\n- **Details:**\n\n  Configure the matching context for `include` and `exclude`.\n\n### include\n\n- **Type:** `string | string[]`\n- **Default：** `['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']` (Relative to the root directory)\n- **Details:**\n\n  Configure to read mock files, which can be a directory, glob, or an array.\n\n### exclude\n\n- **Type:** `string | string[]`\n- **Default：** `['**/node_modules/**','**/.vscode/**','**/.git/**']`\n- **Details:**\n\n  When reading mock files for configuration, the files that need to be excluded can be a directory, glob, or array.\n\n### reload\n\n- **Type:** `boolean`\n- **Default:** `false`\n- **Details:**\n\n  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.\n\n### cors\n\n- **Type:** `boolean | CorsOptions`\n- **Default:** `true`\n- **Details:**\n\n  Enable by default.\n\n  Configure to `cors`, see [cors](https://github.com/expressjs/cors#configuration-options)\n\n### log\n\n- **Type:** `boolean | 'info' | 'warn' | 'error' | 'silent' | 'debug'`\n- **Default:** `info`\n- **Details:**\n\n  Enable log and configure log level.\n\n### formidableOptions\n\n- **Type:** `formidable.Options`\n- **Details:**\n\n  Configure to `formidable`, see [formidable options](https://github.com/node-formidable/formidable#options)\n\n  example: Configure to file upload dir\n\n  ``` ts\n  MockDevServerPlugin({\n    formidableOptions: {\n      uploadDir: path.join(process.cwd(), 'uploads'),\n    }\n  })\n  ```\n\n### cookiesOptions\n\n- **Type:** `CookiesOptions`\n- **Details:**\n\n  Configure to `cookies`, see [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options)\n\n### bodyParserOptions\n\n- **Type:** `BodyParserOptions`\n- **Details:**\n\n  Configure to `co-body`, see [co-body](https://github.com/cojs/co-body#options)\n\n### build\n\n- **Type:** `boolean | ServerBuildOptions`\n- **Default:** `false`\n- **Details:**\n\n  The configuration needed to build a small, independently deployable mock service.\n\n  ``` ts\n  interface ServerBuildOptions {\n    /**\n     * server port\n     * @default 8080\n     */\n    serverPort?: number\n    /**\n     * build output dir\n     * @default 'mockServer'\n     */\n    dist?: string\n    /**\n     * log level\n     * @default 'error'\n     */\n    log?: LogLevel\n  }\n  ```\n\n### priority\n\n- **Type:** `MockMatchPriority`\n- **Details:**\n\n  Custom path matching rule priority。[read more](#custom-path-matching-priority)\n\n## Mock Options\n\n**http mock**\n\n```ts\nimport { defineMock } from 'vite-plugin-mock-dev-server'\nexport default defineMock({\n  url: '/api/test',\n  body: { message: 'hello world' }\n})\n```\n\n**websocket mock**\n\n```ts\nimport { defineMock } from 'vite-plugin-mock-dev-server'\nexport default defineMock({\n  url: '/socket.io',\n  ws: true,\n  setup(wss) {\n    wss.on('connection', (ws, req) =\u003e {\n      console.log('connected')\n    })\n  }\n})\n```\n\n### options.url\n\n- **Type:** `string`\n- **Details:**\n\n  The interface address that needs to be mocked, supported by [path-to-regexp](https://github.com/pillarjs/path-to-regexp) for path matching.\n\n### options.enabled\n\n- **Type:** `boolean`\n- **Default:** `true`\n- **Details:**\n\n  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.\n  Therefore, it is important to be able to configure whether to enable it or not.\n\n### options.method\n\n- **Type:** `Method | Method[]`\n\n  ```ts\n  type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH'\n  ```\n\n- **Default:** `['GET', 'POST']`\n- **Details:**\n\n  The interface allows request methods\n\n### options.type\n\n- **Type:** `'text' | 'json' | 'buffer' | string`\n- **Details:**\n\n  Response body data type. And also support types included in [mime-db](https://github.com/jshttp/mime-db).\n\n  When the response body returns a file and you are not sure which type to use,\n  you can pass the file name as the value. The plugin will internally search for matching\n  `content-type` based on the file name suffix.\n\n### options.headers\n\n- **Type:** `object | (request: MockRequest) =\u003e object | Promise\u003cobject\u003e`\n- **Default:** `{ 'Content-Type': 'application/json' }`\n- **Details:**\n\n  Configure the response body headers\n\n### options.status\n\n- **Type:** `number`\n- **Default:** `200`\n- **Details:**\n\n  Configure Response Header Status Code\n\n### options.statusText\n\n- **Type:** `string`\n- **Default:** `\"OK\"`\n- **Details:**\n\n  Configure response header status text\n\n### options.delay\n\n- **Type:** `number | [number, number]`\n- **Default:** `0`\n- **Details:**\n\n  Configure response delay time, If an array is passed in, it represents the range of delay time.\n\n  unit: `ms`\n\n### options.body\n\n- **Type:** `Body | (request: MockRequest) =\u003e Body | Promise\u003cBody\u003e`\n\n  ```ts\n  type Body = string | object | Buffer | Readable\n  ```\n\n- **Details:**\n\n  Configure response body data content.  `body` takes precedence over `response`.\n\n### options.response\n\n- **Type:** `(req: MockRequest, res: MockResponse, next: (err?: any) =\u003e void) =\u003e void | Promise\u003cvoid\u003e`\n- **Details:**\n\n  If you need to set complex response content, you can use the response method,\n  which is a middleware. Here, you can get information such as req\n  and res of the http request,\n  and then return response data through res.write() | res.end().\n  Otherwise, you need to execute next() method.\n  In `req`, you can also get parsed request information such as\n  `query`, `params`, `body` and `refererQuery`.\n\n### options.cookies\n\n- **Type:** `CookiesOptions | (request: MockRequest) =\u003e CookiesOptions | Promise\u003cCookiesOptions\u003e`\n\n  ```ts\n  type CookiesOptions = Record\u003cstring, CookieValue\u003e\n\n  type CookieValue = string | [string, SetCookie]\n  ```\n\n- **Details:**\n\n  Configure response body cookies\n\n### options.validator\n\n- **Type:** `Validator | (request: MockRequest) =\u003e boolean`\n\n  ```ts\n  interface Validator {\n    /**\n     * The query string located after `?` in the request address has been parsed into JSON.\n     */\n    query: Record\u003cstring, any\u003e\n    /**\n     * The queryString located after `?` in the referer request has been parsed as JSON.\n     */\n    refererQuery: Record\u003cstring, any\u003e\n    /**\n     * Body data in the request\n     */\n    body: Record\u003cstring, any\u003e\n    /**\n     * The params parameter parsed from the `/api/id/:id` in the request address.\n     */\n    params: Record\u003cstring, any\u003e\n    /**\n     * headers data in the request\n     */\n    headers: Headers\n  }\n  ```\n\n- **Details:**\n\n  Request Validator\n\n  Sometimes, for the same API request, data needs to be returned based\n  on different request parameters.\n\n  However, if all of this is written in a single mock's body or response,\n  the content can become cumbersome and difficult to manage.\n  The function of a validator allows you to configure multiple mocks with\n  the same URL simultaneously and determine which mock should be used through validation.\n\n### options.ws\n\n- **Type:** `boolean`\n- **Default:** `false`\n- **Details:**\n\n  Enable WebSocket interface simulation\n\n### options.setup\n\n- **Type:** `(wss: WebSocketServer, ctx: WebSocketSetupContext) =\u003e void`\n- **Details:**\n\n  Configure Websocket Server\n\n```ts\ninterface WebSocketSetupContext {\n  /**\n   * When defining WSS, you may perform some automatic or looping tasks.\n   * However, when hot updating, the plugin will re-execute `setup()`,\n   * which may result in duplicate registration of listening events and looping tasks\n   * such as setTimeout. You can use `onCleanup()` to clear these automatic or looping tasks.\n   */\n  onCleanup: (cleanup: () =\u003e void) =\u003e void\n}\n```\n\n## Request/Response Enhance\n\nWhen defining methods using `headers`, `body`, and `response`, the plugin adds new content to the `request` and `response` parameters.\n\n**In Request:**\n\nThe original type of `request` is [`http.IncomingMessage`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/connect/index.d.ts). The plugin adds data such as `query`, `params`, `body`, `refererQuery`, and the `getCookie(name)` method for obtaining cookie information on this basis.\n\n```ts\ntype Request = http.IncomingMessage \u0026 {\n  query: object\n  params: object\n  body: any\n  refererQuery: object\n  getCookie: (name: string, option?: Cookies.GetOption) =\u003e string | undefined\n}\n```\n\n**In Response:**\n\nThe original type of `response` is `http.ServerResponse\u003chttp.IncomingMessage\u003e`. The plugin adds `setCookie(name, value)` method for configuration cookies on this basis.\n\n``` ts\ntype Response = http.ServerResponse\u003chttp.IncomingMessage\u003e \u0026 {\n  setCookie: (\n    name: string,\n    value?: string | null,\n    option?: Cookies.SetOption,\n  ) =\u003e void\n}\n```\n\n## Share Mock Data\n\nDue to each `mock` file being compiled as a separate entry point, the local files they depend on are also compiled within. Additionally, each mock file has an independent scope. This means that even if multiple mock files collectively depend on a `data.ts` file, they cannot share data. If one mock file modifies the data in `data.ts`, other mock files will not receive the updated data.\n\nTo address this, the plugin offers a `defineMockData` function, which allows using `data.ts` as a shared data source within mock files.\n\n```ts\ntype defineMockData\u003cT\u003e = (\n  key: string, // key\n  initialData: T, // initial data\n) =\u003e [getter, setter] \u0026 { value: T }\n```\n\n### Examples\n\n`data.ts`\n\n```ts\nimport { defineMockData } from 'vite-plugin-mock-dev-server'\n\nexport default defineMockData('posts', [\n  { id: '1', title: 'title1', content: 'content1' },\n  { id: '2', title: 'title2', content: 'content2' },\n])\n```\n\n`*.mock.ts`\n\n```ts\nimport { defineMock } from 'vite-plugin-mock-dev-server'\nimport posts from './data'\n\nexport default defineMock([\n  {\n    url: '/api/posts',\n    body: () =\u003e posts.value\n  },\n  {\n    url: '/api/posts/delete/:id',\n    body: (params) =\u003e {\n      const id = params.id\n      posts.value = posts.value.filter(post =\u003e post.id !== id)\n      return { success: true }\n    }\n  }\n])\n```\n\n\u003e **Tips：**\n\u003e\n\u003e The `defineMockData` function relies solely on the shared data support provided by `memory`.\n\u003e If persistent mock data is required, it is recommended to use a `nosql` database like `lowdb` or `level`.\n\n## Custom-Path-Matching-Priority\n\n\u003e Custom rules only affect links with dynamic parameters, such as: `/api/user/:id`\n\nThe priority of the path matching rules built into the plugin can already meet most needs, but if you need more flexible customization of the matching rule priority, you can use the `priority` parameter.\n\nExp：\n\n```ts\nimport { defineConfig } from 'vite'\nimport mockPlugin from 'vite-plugin-mock-dev-server'\n\nexport default defineConfig({\n  plugins: [\n    mockPlugin({\n      priority: {\n        // The priority of matching rules is global.\n        // The rules declared in this option will take priority over the default rules.\n        // The higher the position of the rule in the array, the higher the priority.\n        global: ['/api/:a/b/c', '/api/a/:b/c', '/api/a/b/:c'],\n        // For some special cases where the priority of certain rules needs to be adjusted,\n        // this option can be used. For example, when a request matches both Rule A and Rule B,\n        // and Rule A has a higher priority than Rule B, but it is desired for Rule B to take effect.\n        special: {\n          // When both A and B or C match, and B or C is at the top of the sort order,\n          // insert A into the top position.\n          // The `when` option is used to further constrain the priority adjustment to\n          // be effective only for certain requests.\n          '/api/:a/:b/c': {\n            rules: ['/api/a/:b/:c', '/api/a/b/:c'],\n            when: ['/api/a/b/c']\n          },\n          // If no `when` is specified, it means that all requests matching the rules need to have their priorities adjusted. It can be abbreviated as `[key]: [...rules]`\n          '/api/:a/b': ['/api/a/:b'],\n        }\n      }\n    })\n  ]\n})\n```\n\n\u003e **Tip:**\n\u003e\n\u003e `priority` although it can adjust the priority,\n\u003e most of the time you do not need to do so. For some special requests,\n\u003e you can use static rules instead of `priority`,\n\u003e as static rules always have the highest priority.\n\n## Examples\n\n`mock/**/*.mock.{ts,js,mjs,cjs,json,json5}`\n\nSee more examples： [example](/example/)\n\n**exp:** Match `/api/test`, And returns a response body content with empty data\n\n``` ts\nexport default defineMock({\n  url: '/api/test',\n})\n```\n\n**exp:** Match `/api/test` , And returns a static content data\n\n``` ts\nexport default defineMock({\n  url: '/api/test',\n  body: { a: 1 },\n})\n```\n\n**exp:** Only Support `GET` Method\n\n``` ts\nexport default defineMock({\n  url: '/api/test',\n  method: 'GET'\n})\n```\n\n**exp:** In the response header, add a custom header and cookie\n\n``` ts\nexport default defineMock({\n  url: '/api/test',\n  headers: { 'X-Custom': '12345678' },\n  cookies: { 'my-cookie': '123456789' },\n})\n```\n\n``` ts\nexport default defineMock({\n  url: '/api/test',\n  headers({ query, body, params, headers }) {\n    return { 'X-Custom': query.custom }\n  },\n  cookies() {\n    return { 'my-cookie': '123456789' }\n  }\n})\n```\n\n**exp:** Define multiple mock requests for the same URL and match valid rules with validators\n\n``` ts\nexport default defineMock([\n  // Match /api/test?a=1\n  {\n    url: '/api/test',\n    validator: {\n      query: { a: 1 },\n    },\n    body: { message: 'query.a == 1' },\n  },\n  // Match /api/test?a=2\n  {\n    url: '/api/test',\n    validator: {\n      query: { a: 2 },\n    },\n    body: { message: 'query.a == 2' },\n  },\n  {\n    // `?a=3` will resolve to `validator.query`\n    url: '/api/test?a=3',\n    body: { message: 'query.a == 3' }\n  },\n  // Hitting the POST /api/test request, and in the request body,\n  // field a is an array that contains items with values of 1 and 2.\n  {\n    url: '/api/test',\n    method: ['POST'],\n    validator: { body: { a: [1, 2] } }\n  }\n])\n```\n\n**exp:** Response Delay\n\n``` ts\nexport default defineMock({\n  url: '/api/test',\n  delay: 6000, // delay 6 seconds\n})\n```\n\n**exp:** The interface request failed\n\n``` ts\nexport default defineMock({\n  url: '/api/test',\n  status: 502,\n  statusText: 'Bad Gateway'\n})\n```\n\n**exp:** Dynamic route matching\n\n``` ts\nexport default defineMock({\n  url: '/api/user/:userId',\n  body({ params }) {\n    return { userId: params.userId }\n  }\n})\n```\n\nThe `userId` in the route will be resolved into the `request.params` object.\n\n**exp:** Use the buffer to respond data\n\n```ts\nimport { Buffer } from 'node:buffer'\n\n// Since the default value of type is json,\n// although buffer is used for body during transmission,\n// the content-type is still json.\nexport default defineMock({\n  url: 'api/buffer',\n  body: Buffer.from(JSON.stringify({ a: 1 }))\n})\n```\n\n``` ts\n// When the type is buffer, the content-type is application/octet-stream.\n// The data passed in through body will be converted to a buffer.\nexport default defineMock({\n  url: 'api/buffer',\n  type: 'buffer',\n  // Convert using Buffer.from(body) for internal use\n  body: { a: 1 }\n})\n```\n\n**exp:** Response file type\n\nSimulate file download, and pass in the file reading stream.\n\n``` ts\nimport { createReadStream } from 'node:fs'\n\nexport default defineMock({\n  url: '/api/download',\n  // When you are unsure of the type, you can pass in the file name for internal parsing by the plugin.\n  type: 'my-app.dmg',\n  body: () =\u003e createReadStream('./my-app.dmg')\n})\n```\n\n```html\n\u003ca href=\"/api/download\" download=\"my-app.dmg\"\u003eDownload File\u003c/a\u003e\n```\n\n**exp:** Use `mockjs`:\n\n``` ts\nimport Mock from 'mockjs'\n\nexport default defineMock({\n  url: '/api/test',\n  body: Mock.mock({\n    'list|1-10': [{\n      'id|+1': 1\n    }]\n  })\n})\n```\n\nYou need install `mockjs`\n\n**exp:** Use `response` to customize the response\n\n``` ts\nexport default defineMock({\n  url: '/api/test',\n  response(req, res, next) {\n    const { query, body, params, headers } = req\n    console.log(query, body, params, headers)\n\n    res.status = 200\n    res.setHeader('Content-Type', 'application/json')\n    res.end(JSON.stringify({\n      query,\n      body,\n      params,\n    }))\n  }\n})\n```\n\n**exp:** Use json / json5\n\n``` json\n{\n  \"url\": \"/api/test\",\n  \"body\": {\n    \"a\": 1\n  }\n}\n```\n\n**exp:** multipart, upload files.\n\nuse [`formidable`](https://www.npmjs.com/package/formidable#readme) to support.\n\n``` html\n\u003cform action=\"/api/upload\" method=\"post\" enctype=\"multipart/form-data\"\u003e\n  \u003cp\u003e\n    \u003cspan\u003efile: \u003c/span\u003e\n    \u003cinput type=\"file\" name=\"files\" multiple=\"multiple\"\u003e\n  \u003c/p\u003e\n  \u003cp\u003e\n    \u003cspan\u003ename:\u003c/span\u003e\n    \u003cinput type=\"text\" name=\"name\" value=\"mark\"\u003e\n  \u003c/p\u003e\n  \u003cp\u003e\n    \u003cinput type=\"submit\" value=\"submit\"\u003e\n  \u003c/p\u003e\n\u003c/form\u003e\n```\n\nfields `files` mapping to `formidable.File`\n\n``` ts\nexport default defineMock({\n  url: '/api/upload',\n  method: 'POST',\n  body(req) {\n    const body = req.body\n    return {\n      name: body.name,\n      files: body.files.map((file: any) =\u003e file.originalFilename),\n    }\n  },\n})\n```\n\n**exp:** Graphql\n\n``` ts\nimport { buildSchema, graphql } from 'graphql'\n\nconst schema = buildSchema(`\ntype Query {\n  hello: String\n}\n`)\nconst rootValue = { hello: () =\u003e 'Hello world!' }\n\nexport default defineMock({\n  url: '/api/graphql',\n  method: 'POST',\n  body: async (request) =\u003e {\n    const source = request.body.source\n    const { data } = await graphql({ schema, rootValue, source })\n    return data\n  },\n})\n```\n\n``` ts\nfetch('/api/graphql', {\n  method: 'POST',\n  body: JSON.stringify({ source: '{ hello }' })\n})\n```\n\n**exp:** WebSocket Mock\n\n``` ts\n// ws.mock.ts\nexport default defineMock({\n  url: '/socket.io',\n  ws: true,\n  setup(wss, { onCleanup }) {\n    const wsMap = new Map()\n    wss.on('connection', (ws, req) =\u003e {\n      const token = req.getCookie('token')\n      wsMap.set(token, ws)\n      ws.on('message', (raw) =\u003e {\n        const data = JSON.parse(String(raw))\n        if (data.type === 'ping')\n          return\n        // Broadcast\n        for (const [_token, _ws] of wsMap.entires()) {\n          if (_token !== token)\n            _ws.send(raw)\n        }\n      })\n    })\n    wss.on('error', (err) =\u003e {\n      console.error(err)\n    })\n    onCleanup(() =\u003e wsMap.clear())\n  }\n})\n```\n\n``` ts\n// app.ts\nconst ws = new WebSocket('ws://localhost:5173/socket.io')\nws.addEventListener('open', () =\u003e {\n  setInterval(() =\u003e {\n    // heartbeat\n    ws.send(JSON.stringify({ type: 'ping' }))\n  }, 1000)\n}, { once: true })\nws.addEventListener('message', (raw) =\u003e {\n  console.log(raw)\n})\n```\n\n**exp：** EventSource Mock\n\n```ts\n// sse.mock.ts\nimport { createSSEStream, defineMock } from 'vite-plugin-mock-dev-server'\n\nexport default defineMock({\n  url: '/api/sse',\n  response(req, res) {\n    const sse = createSSEStream(req, res)\n    let count = 0\n    const timer = setInterval(() =\u003e {\n      sse.write({\n        event: 'count',\n        data: { count: ++count },\n      })\n      if (count \u003e= 10) {\n        sse.end()\n        clearInterval(timer)\n      }\n    }, 1000)\n  },\n})\n```\n\n```ts\n// app.js\nconst es = new EventSource('/api/sse')\n\nes.addEventListener('count', (e) =\u003e {\n  console.log(e.data)\n})\n```\n\n## Mock Services\n\nIn some scenarios, it may be necessary to use the data provided by mock services for display purposes, but the project may have already been packaged, built and deployed without support from `Vite` and this plugin's mock service. Since this plugin supports importing various `node` modules in mock files at the design stage, the mock file cannot be inline into client build code.\n\nTo meet such scenarios, on one hand, the plugin provides support under `vite preview`, and on the other hand, it also builds a small independent mock service application that can be deployed to relevant environments during `vite build`. This can then be forwarded through other HTTP servers like Nginx to actual ports for mock support.\n\nThe default output is built into the directory `dist/mockServer`, generating files as follows:\n\n``` sh\n./mockServer\n├── index.js\n├── mock-data.js\n└── package.json\n```\n\nIn this directory, execute `npm install` to install dependencies, and then execute `npm start` to start the mock server.\n\nThe default port is `8080`.\n\nYou can access related `mock` interfaces through `localhost:8080/`.\n\n## Links\n\n- [vite](https://vitejs.dev/)\n- [awesome-vite](https://github.com/vitejs/awesome-vite#helpers)\n- [rspack-plugin-mock](https://github.com/pengzhanbo/rspack-plugin-mock) - **Rspack** and **Rsbuild** plugin for API mock server\n\n## Contributors\n\n\u003c!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section --\u003e\n[![All Contributors](https://img.shields.io/badge/all_contributors-6-orange.svg?style=flat-square)](#contributors)\n\u003c!-- ALL-CONTRIBUTORS-BADGE:END --\u003e\n\n\u003c!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --\u003e\n\u003c!-- prettier-ignore-start --\u003e\n\u003c!-- markdownlint-disable --\u003e\n\u003ctable\u003e\n  \u003ctbody\u003e\n    \u003ctr\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://pengzhanbo.cn\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/16745751?v=4?s=100\" width=\"100px;\" alt=\"pengzhanbo\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003epengzhanbo\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=pengzhanbo\" title=\"Documentation\"\u003e📖\u003c/a\u003e \u003ca href=\"#ideas-pengzhanbo\" title=\"Ideas, Planning, \u0026 Feedback\"\u003e🤔\u003c/a\u003e \u003ca href=\"#example-pengzhanbo\" title=\"Examples\"\u003e💡\u003c/a\u003e \u003ca href=\"https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=pengzhanbo\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://github.com/jiadesen\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/22772994?v=4?s=100\" width=\"100px;\" alt=\"jiadesen\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003ejiadesen\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"#ideas-jiadesen\" title=\"Ideas, Planning, \u0026 Feedback\"\u003e🤔\u003c/a\u003e \u003ca href=\"https://github.com/pengzhanbo/vite-plugin-mock-dev-server/issues?q=author%3Ajiadesen\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://github.com/yogibaba\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/152670?v=4?s=100\" width=\"100px;\" alt=\"yogibaba\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eyogibaba\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=yogibaba\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://github.com/pfdgithub\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/3262762?v=4?s=100\" width=\"100px;\" alt=\"pfdgithub\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003epfdgithub\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=pfdgithub\" title=\"Code\"\u003e💻\u003c/a\u003e \u003ca href=\"https://github.com/pengzhanbo/vite-plugin-mock-dev-server/issues?q=author%3Apfdgithub\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://github.com/chuyuandu\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/6959138?v=4?s=100\" width=\"100px;\" alt=\"chuyuan du\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003echuyuan du\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=chuyuandu\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n      \u003ctd align=\"center\" valign=\"top\" width=\"14.28%\"\u003e\u003ca href=\"https://www.hlwen.com\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/13469676?v=4?s=100\" width=\"100px;\" alt=\"hlwen\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003ehlwen\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/pengzhanbo/vite-plugin-mock-dev-server/issues?q=author%3Ahlwen\" title=\"Bug reports\"\u003e🐛\u003c/a\u003e \u003ca href=\"https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=hlwen\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n    \u003c/tr\u003e\n  \u003c/tbody\u003e\n\u003c/table\u003e\n\n\u003c!-- markdownlint-restore --\u003e\n\u003c!-- prettier-ignore-end --\u003e\n\n\u003c!-- ALL-CONTRIBUTORS-LIST:END --\u003e\n\u003c!-- prettier-ignore-start --\u003e\n\u003c!-- markdownlint-disable --\u003e\n\n\u003c!-- markdownlint-restore --\u003e\n\u003c!-- prettier-ignore-end --\u003e\n\n\u003c!-- ALL-CONTRIBUTORS-LIST:END --\u003e\n\n## LICENSE\n\nThe plugin is licensed under the [MIT License](./LICENSE)\n\n[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server?ref=badge_large)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server/lists"}