{"id":13485026,"url":"https://github.com/vbenjs/vite-plugin-mock","last_synced_at":"2025-12-30T10:49:06.589Z","repository":{"id":38352975,"uuid":"295185311","full_name":"vbenjs/vite-plugin-mock","owner":"vbenjs","description":"A mock plugin for vite.use mockjs.","archived":false,"fork":false,"pushed_at":"2024-07-24T14:31:10.000Z","size":503,"stargazers_count":642,"open_issues_count":62,"forks_count":97,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-04-03T18:15:14.703Z","etag":null,"topics":[],"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/vbenjs.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":"2020-09-13T15:55:48.000Z","updated_at":"2025-03-25T08:52:18.000Z","dependencies_parsed_at":"2024-01-03T11:42:20.693Z","dependency_job_id":"f371cf1c-5e19-426e-95df-56d7398a4a5e","html_url":"https://github.com/vbenjs/vite-plugin-mock","commit_stats":{"total_commits":109,"total_committers":25,"mean_commits":4.36,"dds":0.5779816513761468,"last_synced_commit":"ca2e9eabf1704f2e1bbb33f4cd66bfd440c90828"},"previous_names":["anncwb/vite-plugin-mock"],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vbenjs%2Fvite-plugin-mock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vbenjs%2Fvite-plugin-mock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vbenjs%2Fvite-plugin-mock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vbenjs%2Fvite-plugin-mock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vbenjs","download_url":"https://codeload.github.com/vbenjs/vite-plugin-mock/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248606867,"owners_count":21132430,"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":[],"created_at":"2024-07-31T17:01:43.095Z","updated_at":"2025-12-30T10:49:06.559Z","avatar_url":"https://github.com/vbenjs.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# vite-plugin-mock\n\n**English** | [中文](./README.zh_CN.md)\n\n[![npm][npm-img]][npm-url] [![node][node-img]][node-url]\n\nProvide local and prod mocks for vite.\n\nA mock plugin for vite, developed based on mockjs. And support the local environment and production environment at the same time. Connect service middleware is used locally, mockjs is used online\n\n### Install (yarn or npm)\n\n**node version:** \u003e=12.0.0\n\n**vite version:** \u003e=2.0.0\n\n```bash\nyarn add mockjs\n# or\nnpm i  mockjs -S\n# or\npnpm add mockjs\n```\n\nand\n\n```bash\nyarn add vite-plugin-mock -D\n# or\nnpm i vite-plugin-mock -D\n# or\npnpm add vite-plugin-mock -D\n```\n\n### Example\n\n**Run Example**\n\n```bash\n\n# ts example\ncd ./examples/ts-examples\n\nyarn install\n\nyarn serve\n\n# js example\n\ncd ./examples/js-examples\n\nyarn install\n\nyarn serve\n```\n\n## Usage\n\n**Development environment**\n\nThe development environment is implemented using Connect middleware。\n\nDifferent from the production environment, you can view the network request record in the Google Chrome console\n\n- Config plugin in vite.config.ts\n\n```ts\nimport { UserConfigExport, ConfigEnv } from 'vite'\n\nimport { viteMockServe } from 'vite-plugin-mock'\nimport vue from '@vitejs/plugin-vue'\n\nexport default ({ command }: ConfigEnv): UserConfigExport =\u003e {\n  return {\n    plugins: [\n      vue(),\n      viteMockServe({\n        // default\n        mockPath: 'mock',\n        enable: true,\n      }),\n    ],\n  }\n}\n```\n\n- viteMockServe Options\n\n```ts\n{\n    mockPath?: string;\n    ignore?: RegExp | ((fileName: string) =\u003e boolean);\n    watchFiles?: boolean;\n    enable?: boolean;\n    ignoreFiles?: string[];\n    configPath?: string;\n}\n```\n\n## Options\n\n### mockPath\n\n**type:** `string`\n\n**default:** `'mock'`\n\nSet the folder where the mock .ts file is stored\n\nIf `watchFiles:true`, the file changes in the folder will be monitored. And synchronize to the request result in real time\n\nIf configPath has a value, it is invalid\n\n### ignore\n\n**type:** `RegExp | ((fileName: string) =\u003e boolean);`\n\n**default:** `undefined`\n\nWhen automatically reading analog .ts files, ignore files in the specified format\n\n### watchFiles\n\n**type:** `boolean`\n\n**default:** `true`\n\nSet whether to monitor changes in mock .ts files\n\n### enable\n\n**type:** `boolean`\n\n**default:** true\n\nWhether to enable the mock function\n\n### configPath\n\n**type:** `string`\n\n**default:** `vite.mock.config.ts`\n\nSet the data entry that the mock reads. When the file exists and is located in the project root directory, the file will be read and used first. The configuration file returns an array\n\n### logger\n\n**type:** `boolean`\n\n**default:** `true`\n\nWhether to display the request log on the console\n\n## Mock file example\n\n`/path/mock`\n\n```ts\n// test.ts\n\nimport { MockMethod, MockConfig } from 'vite-plugin-mock'\nexport default [\n  {\n    url: '/api/get',\n    method: 'get',\n    response: ({ query }) =\u003e {\n      return {\n        code: 0,\n        data: {\n          name: 'vben',\n        },\n      }\n    },\n  },\n  {\n    url: '/api/post',\n    method: 'post',\n    timeout: 2000,\n    response: {\n      code: 0,\n      data: {\n        name: 'vben',\n      },\n    },\n  },\n  {\n    url: '/api/text',\n    method: 'post',\n    rawResponse: async (req, res) =\u003e {\n      let reqbody = ''\n      await new Promise((resolve) =\u003e {\n        req.on('data', (chunk) =\u003e {\n          reqbody += chunk\n        })\n        req.on('end', () =\u003e resolve(undefined))\n      })\n      res.setHeader('Content-Type', 'text/plain')\n      res.statusCode = 200\n      res.end(`hello, ${reqbody}`)\n    },\n  },\n] as MockMethod[]\n\nexport default function (config: MockConfig) {\n  return [\n    {\n      url: '/api/text',\n      method: 'post',\n      rawResponse: async (req, res) =\u003e {\n        let reqbody = ''\n        await new Promise((resolve) =\u003e {\n          req.on('data', (chunk) =\u003e {\n            reqbody += chunk\n          })\n          req.on('end', () =\u003e resolve(undefined))\n        })\n        res.setHeader('Content-Type', 'text/plain')\n        res.statusCode = 200\n        res.end(`hello, ${reqbody}`)\n      },\n    },\n  ]\n}\n```\n\n### MockMethod\n\n```ts\n{\n  // request url\n  url: string;\n  // request method\n  method?: MethodType;\n  // Request time in milliseconds\n  timeout?: number;\n  // default: 200\n  statusCode?:number;\n  // response data (JSON)\n  response?: ((opt: { [key: string]: string; body: Record\u003cstring,any\u003e; query:  Record\u003cstring,any\u003e, headers: Record\u003cstring, any\u003e; }) =\u003e any) | any;\n  // response (non-JSON)\n  rawResponse?: (req: IncomingMessage, res: ServerResponse) =\u003e void;\n}\n\n```\n\n### Example (3.0.0 recommended)\n\nCreate the `mockProdServer.ts` file\n\n```ts\n//  mockProdServer.ts\n\nimport { createProdMockServer } from 'vite-plugin-mock/client'\n\n// Import your mock .ts files one by one\n// If you use vite.mock.config.ts, just import the file directly\n// You can use the import.meta.glob function to import all\nimport testModule from '../mock/test'\n\nexport function setupProdMockServer() {\n  createProdMockServer([...testModule])\n}\n```\n\nConfig `vite-plugin-mock`\n\n```ts\nimport { viteMockServe } from 'vite-plugin-mock'\n\nimport { UserConfigExport, ConfigEnv } from 'vite'\n\nexport default ({ command }: ConfigEnv): UserConfigExport =\u003e {\n  return {\n    plugins: [\n      viteMockServe({\n        mockPath: 'mock',\n        // According to the project configuration. Can be configured in the .env file\n        enable: true,\n      }),\n    ],\n  }\n}\n```\n\n## Sample project\n\n[Vben Admin](https://github.com/anncwb/vue-vben-admin)\n\n## Note\n\n- The node module cannot be used in the mock .ts file, otherwise the production environment will fail\n- Mock is used in the production environment, which is only suitable for some test environments. Do not open it in the formal environment to avoid unnecessary errors. At the same time, in the production environment, it may affect normal Ajax requests, such as file upload failure, etc.\n\n## License\n\nMIT\n\n[npm-img]: https://img.shields.io/npm/v/vite-plugin-mock.svg\n[npm-url]: https://npmjs.com/package/vite-plugin-mock\n[node-img]: https://img.shields.io/node/v/vite-plugin-mock.svg\n[node-url]: https://nodejs.org/en/about/releases/\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvbenjs%2Fvite-plugin-mock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvbenjs%2Fvite-plugin-mock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvbenjs%2Fvite-plugin-mock/lists"}