{"id":14054214,"url":"https://github.com/pengzhanbo/rspack-plugin-mock","last_synced_at":"2025-12-25T18:56:41.442Z","repository":{"id":251309463,"uuid":"837028259","full_name":"pengzhanbo/rspack-plugin-mock","owner":"pengzhanbo","description":"inject api mock server to rspack/rsbuild development server","archived":false,"fork":false,"pushed_at":"2024-12-18T03:49:33.000Z","size":255,"stargazers_count":6,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-16T23:51:16.811Z","etag":null,"topics":["mock","mock-server","plugin","rsbuild","rspack"],"latest_commit_sha":null,"homepage":"","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":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-08-02T04:15:01.000Z","updated_at":"2025-03-15T19:02:20.000Z","dependencies_parsed_at":"2024-10-17T21:08:27.482Z","dependency_job_id":"687cd9d3-3e78-4efa-b70d-c2e4cfaafd16","html_url":"https://github.com/pengzhanbo/rspack-plugin-mock","commit_stats":null,"previous_names":["pengzhanbo/rspack-plugin-mock"],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pengzhanbo%2Frspack-plugin-mock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pengzhanbo%2Frspack-plugin-mock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pengzhanbo%2Frspack-plugin-mock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pengzhanbo%2Frspack-plugin-mock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pengzhanbo","download_url":"https://codeload.github.com/pengzhanbo/rspack-plugin-mock/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244310790,"owners_count":20432612,"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":["mock","mock-server","plugin","rsbuild","rspack"],"created_at":"2024-08-12T21:00:57.227Z","updated_at":"2025-12-25T18:56:41.437Z","avatar_url":"https://github.com/pengzhanbo.png","language":"TypeScript","funding_links":[],"categories":["Plugins","TypeScript"],"sub_categories":["Rspack Plugins"],"readme":"# rspack-plugin-mock\n\n[Rspack](https://rspack.dev) and [Rsbuild](https://rsbuild.dev) plugin for API mock dev server.\n\nImplement a mock-dev-server in `rspack` and `rsbuild` that is fully consistent with [vite-plugin-mock-dev-server](https://github.com/pengzhanbo/vite-plugin-mock-dev-server).\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://www.npmjs.com/package/rspack-plugin-mock\"\u003e\u003cimg alt=\"npm\" src=\"https://img.shields.io/npm/v/rspack-plugin-mock?style=flat-square\u0026colorA=564341\u0026colorB=EDED91\"\u003e\u003c/a\u003e\n  \u003cimg alt=\"node-current\" src=\"https://img.shields.io/node/v/rspack-plugin-mock?style=flat-square\u0026colorA=564341\u0026colorB=EDED91\"\u003e\n  \u003cimg alt=\"npm peer dependency version\" src=\"https://img.shields.io/npm/dependency-version/rspack-plugin-mock/peer/@rspack/core?style=flat-square\u0026colorA=564341\u0026colorB=EDED91\u0026label=rspack\"\u003e\n  \u003cimg alt=\"npm peer dependency version\" src=\"https://img.shields.io/npm/dependency-version/rspack-plugin-mock/peer/@rsbuild/core?style=flat-square\u0026colorA=564341\u0026colorB=EDED91\u0026label=rsbuild\"\u003e\n  \u003cimg alt=\"npm\" src=\"https://img.shields.io/npm/dm/rspack-plugin-mock?style=flat-square\u0026colorA=564341\u0026colorB=EDED91\"\u003e\n  \u003cimg alt=\"GitHub Workflow Status\" src=\"https://img.shields.io/github/actions/workflow/status/pengzhanbo/rspack-plugin-mock/release.yaml?style=flat-square\u0026colorA=564341\u0026colorB=EDED91\"\u003e\n\u003c/p\u003e\n\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\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 `devServer.proxy` in rspack, or `server.proxy` in rsbuild.\n- 🍕 Support `define` in the mock file.\n- ⚓️ Support `alias` in the mock file.\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## Install\n\n```sh\n# npm\nnpm i -D rspack-plugin-mock\n# yarn\nyarn add rspack-plugin-mock\n# pnp\npnpm add -D rspack-plugin-mock\n```\n\n### Usage\n\n**In Rspack**\n\n```ts\n// rspack.config.js\nimport { MockServerPlugin } from 'rspack-plugin-mock'\n\nexport default {\n  devServer: {\n    // The plugin will read the `proxy` option from the `devServer`\n    proxy: [\n      { context: '/api', target: 'http://example.com' },\n    ],\n  },\n  plugins: [\n    new MockServerPlugin(/* pluginOptions */),\n  ]\n}\n```\n\n**In Rsbuild**\n\n```ts\n// rsbuild.config.ts\nimport { defineConfig } from '@rsbuild/core'\nimport { pluginMockServer } from 'rspack-plugin-mock/rsbuild'\n\nexport default defineConfig({\n  server: {\n    // The plugin will read the `proxy` option from the `server`\n    proxy: {\n      '/api': 'http://example.com',\n    },\n  },\n  plugins: [\n    pluginMockServer(/* pluginOptions */),\n  ],\n})\n```\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 'rspack-plugin-mock/helper'\n\nexport default defineMock({\n  url: '/api/test',\n  body: { a: 1, b: 2 }\n})\n```\n\nYou can write using file formats such as `.js, .mjs, .cjs, .ts, .json, .json5`.\n\n## Methods\n\n### MockServerPlugin(pluginOptions)\n\nrspack mock server plugin.\n\nThe plugin will read the `devServer` configuration and inject middleware into the http-server of `@rspack/dev-server`.\n\n```js\nimport { MockServerPlugin } from 'rspack-plugin-mock'\n\nexport default {\n  devServer: {\n    // The plugin will read the `proxy` option from the `devServer`\n    proxy: [\n      { context: '/api', target: 'http://example.com' },\n    ],\n  },\n  plugins: [\n    new MockServerPlugin(/* pluginOptions */),\n  ]\n}\n```\n\n### pluginMockServer(pluginOptions)\n\nrsbuild mock server plugin. **It is only used in `rsbuild`.**\n\n```ts\n// rsbuild.config.ts\nimport { defineConfig } from '@rsbuild/core'\nimport { pluginMockServer } from 'rspack-plugin-mock/rsbuild'\n\nexport default defineConfig({\n  server: {\n    // The plugin will read the `proxy` option from the `server`\n    proxy: {\n      '/api': 'http://example.com',\n    },\n  },\n  plugins: [\n    pluginMockServer(/* pluginOptions */),\n  ],\n})\n```\n\n### defineMock(options)\n\n- **options:** [`MockOptions | MockOptions[]`](#mock-options)\n\nmock options Type helper\n\n```ts\nimport { defineMock } from 'rspack-plugin-mock/helper'\n\nexport default defineMock({\n  url: '/api/test',\n  body: { a: 1, b: 2 }\n})\n```\n\n### createDefineMock(transformer)\n\n- **transformer:** `(mock: MockOptions) =\u003e MockOptions`\n\nReturn a custom defineMock function to support preprocessing of mock config.\n\n```ts\nimport { createDefineMock } from 'rspack-plugin-mock/helper'\n\nconst definePostMock = createDefineMock((mock) =\u003e {\n  mock.url = `/api/post/${mock.url}`\n})\n\nexport default definePostMock({\n  url: 'list', // =\u003e '/api/post/list'\n  body: [{ title: '1' }, { title: '2' }],\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 'rspack-plugin-mock/helper'\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### options.prefix\n\n- **Type:** `string | string[]`\n- **Details:**\n\n  To configure the path matching rules for http mock services,\n  any request path starting with prefix will be intercepted and proxied.\n  If the prefix starts with `^`, it will be recognized as a `RegExp`.\n\n### options.wsPrefix\n\n- **Type:** `string | string[]`\n- **Details:**\n\n  Configure path matching rules for WebSocket mock service.\n  Any ws/wss requests with a request path starting with wsPrefix\n  will be intercepted by the proxy.\n  If wsPrefix starts with `^`, it will be recognized as a `RegExp`.\n\n  Please avoid having the configurations in `wsPrefix` appear in `devServer.proxy` / `server.proxy`, as this may lead to conflicts in the rules.\n\n### options.cwd\n\n- **Type:** `string`\n- **Default:** `process.cwd()`\n- **Details:**\n\n  Configure the matching context for `include` and `exclude`.\n\n### options.dir\n\n- **Type:** `string`\n- **Default:** `mock` (relative to [`options.cwd`](#optionscwd))\n- **Details:**\n\n  Configure the directory where mock files are located\n\n### options.include\n\n- **Type:** `string | string[]`\n- **Default:** `['**/*.mock.{js,ts,cjs,mjs,json,json5}']` (relative to [`options.dir`](#optionsdir))\n- **Details:**\n\n  glob string matching mock includes files. see [picomatch](https://github.com/micromatch/picomatch#globbing-features)\n\n### options.exclude\n\n- **Type:** `string | string[]`\n- **Default:** `[]`  (relative to [`options.dir`](#optionsdir))\n- **Details:**\n\n  glob string matching mock excluded files. see [picomatch](https://github.com/micromatch/picomatch#globbing-features)\n\n### options.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### options.reload\n\n- **Type:** `boolean`\n- **Default:** `false`\n- **Details:**\n\n  If you want to refresh the page every time you modify a mock file,\n  you can open this option.\n\n### options.cors\n\n- **Type:** `boolean | CorsOptions`\n- **Default:** `true`\n- **Details:**\n\n  Configure to [cors](https://github.com/expressjs/cors#configuration-options)\n\n### options.formidableOptions\n\n- **Type:** `FormidableOptions`\n- **Default:** `{ multiples: true }`\n- **Details:**\n\n  Configure to [formidable](https://github.com/node-formidable/formidable#options)\n\n### options.cookiesOptions\n\n- **Type:** `CookiesOptions`\n- **Details:**\n\n  Configure to [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options)\n\n### options.bodyParserOptions\n\n- **Type:** `BodyParserOptions`\n- **Details:**\n\n  Configure to [co-body](https://github.com/cojs/co-body#options)\n\n## options.build\n\n- **Type:** `boolean | ServerBuildOption`\n\n  ```ts\n  interface ServerBuildOption {\n    /**\n     * Service startup port\n     * @default 8080\n     */\n    serverPort?: number\n    /**\n     * Service application output directory\n     * @default 'mockServer'\n     */\n    dist?: string\n\n    /**\n     * Service application log level\n     * @default 'error'\n     */\n    log?: LogLevel\n  }\n  ```\n\n- **Default:** `false`\n- **Details:**\n\n  When you need to build a small mock service, you can configure this option.\n\n## Mock Options\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### Types\n\n```ts\nexport type MockRequest = http.IncomingMessage \u0026 ExtraRequest\n\nexport type MockResponse = http.ServerResponse\u003chttp.IncomingMessage\u003e \u0026 {\n  /**\n   * Set cookie in response\n   * @see [cookies](https://github.com/pillarjs/cookies#cookiessetname--values--options)\n   */\n  setCookie: (\n    name: string,\n    value?: string | null,\n    option?: Cookies.SetOption,\n  ) =\u003e void\n}\n\ninterface ExtraRequest {\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   * Get the cookie carried in the request.\n   * @see [cookies](https://github.com/pillarjs/cookies#cookiesgetname--options)\n   */\n  getCookie: (name: string, option?: Cookies.GetOption) =\u003e string | undefined\n}\n```\n\n## Examples\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:3000/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 'rspack-plugin-mock/helper'\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 `rspack/rsbuild` 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\nThe plugin support for builds a small independent mock service application that can be deployed to relevant environments during `production 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- [rspack](https://rspack.dev)\n- [rsbuild](https://rsbuild.dev)\n- [vite-plugin-mock-dev-server](https://github.com/pengzhanbo/vite-plugin-mock-dev-server)\n\n## License\n\nrspack-plugin-mock is licensed under the [MIT License](./LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpengzhanbo%2Frspack-plugin-mock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpengzhanbo%2Frspack-plugin-mock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpengzhanbo%2Frspack-plugin-mock/lists"}