0c7f2195c56405fea81ddbd4745a7361787fca373b70545a37c3edfa63089366cb8b5288b79feff34388b94ef13759c5750135d1b0f3a757fb3ebaa14a4029 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. # vite-plugin-mock
  2. **English** | [中文](./README.zh_CN.md)
  3. [![npm][npm-img]][npm-url] [![node][node-img]][node-url]
  4. Provide local and prod mocks for vite.
  5. A 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
  6. ### Install (yarn or npm)
  7. **node version:** >=12.0.0
  8. **vite version:** >=2.0.0
  9. ```bash
  10. yarn add mockjs
  11. # or
  12. npm i mockjs -S
  13. ```
  14. ```bash
  15. yarn add vite-plugin-mock -D
  16. # or
  17. npm i vite-plugin-mock -D
  18. ```
  19. ### Example
  20. **Run Example**
  21. ```bash
  22. # ts example
  23. cd ./examples/ts-examples
  24. yarn install
  25. yarn serve
  26. # js example
  27. cd ./examples/js-examples
  28. yarn install
  29. yarn serve
  30. ```
  31. ## Usage
  32. **Development environment**
  33. The development environment is implemented using Connect middleware。
  34. Different from the production environment, you can view the network request record in the Google Chrome console
  35. - Config plugin in vite.config.ts
  36. ```ts
  37. import { UserConfigExport, ConfigEnv } from 'vite'
  38. import { viteMockServe } from 'vite-plugin-mock'
  39. import vue from '@vitejs/plugin-vue'
  40. export default ({ command }: ConfigEnv): UserConfigExport => {
  41. return {
  42. plugins: [
  43. vue(),
  44. viteMockServe({
  45. // default
  46. mockPath: 'mock',
  47. localEnabled: command === 'serve',
  48. }),
  49. ],
  50. }
  51. }
  52. ```
  53. - viteMockServe Options
  54. ```ts
  55. {
  56. mockPath?: string;
  57. supportTs?: boolean;
  58. ignore?: RegExp | ((fileName: string) => boolean);
  59. watchFiles?: boolean;
  60. localEnabled?: boolean;
  61. ignoreFiles?: string[];
  62. configPath?: string;
  63. prodEnabled?: boolean;
  64. injectFile?: string;
  65. injectCode?: string;
  66. }
  67. ```
  68. ## Options
  69. ### mockPath
  70. **type:** `string`
  71. **default:** `'mock'`
  72. Set the folder where the mock .ts file is stored
  73. If `watchFiles:true`, the file changes in the folder will be monitored. And synchronize to the request result in real time
  74. If configPath has a value, it is invalid
  75. ### supportTs
  76. **type:** `boolean`
  77. **default:** `true`
  78. After opening, the ts file module can be read. Note that you will not be able to monitor .js files after opening.
  79. ### ignore
  80. **type:** `RegExp | ((fileName: string) => boolean);`
  81. **default:** `undefined`
  82. When automatically reading analog .ts files, ignore files in the specified format
  83. ### watchFiles
  84. **type:** `boolean`
  85. **default:** `true`
  86. Set whether to monitor changes in mock .ts files
  87. ### localEnabled
  88. **type:** `boolean`
  89. **default:** `command === 'serve'`
  90. Set whether to enable the local mock .ts file, do not open it in the production environment
  91. ### prodEnabled
  92. **type:** `boolean`
  93. **default:** `command !=='serve'`
  94. Set whether to enable mock function for packaging
  95. ### injectCode
  96. **type:** `string`
  97. **default:**''
  98. If the mock function is enabled in the production environment, that is, `prodEnabled=true`, the code will be injected into the bottom of the file corresponding to `injectFile`. The default is `main.{ts,js}`
  99. The advantage of this is that you can dynamically control whether mock is enabled in the production environment and mock.js will not be packaged when it is not enabled.
  100. If the code is written directly in `main.ts`, no matter whether it is turned on or not, the final package will include `mock.js`
  101. ### injectFile
  102. **type:** `string`
  103. **default:** `path.resolve(process.cwd(),'src/main.{ts,js}')`
  104. The file injected by `injectCode` code, the default is `src/main.{ts,js}` in the project root directory
  105. ### configPath
  106. **type:** `string`
  107. **default:** `vite.mock.config.ts`
  108. Set 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
  109. ### logger
  110. **type:** `boolean`
  111. **default:** `true`
  112. Whether to display the request log on the console
  113. ## Mock file example
  114. `/path/mock`
  115. ```ts
  116. // test.ts
  117. import { MockMethod } from 'vite-plugin-mock'
  118. export default [
  119. {
  120. url: '/api/get',
  121. method: 'get',
  122. response: ({ query }) => {
  123. return {
  124. code: 0,
  125. data: {
  126. name: 'vben',
  127. },
  128. }
  129. },
  130. },
  131. {
  132. url: '/api/post',
  133. method: 'post',
  134. timeout: 2000,
  135. response: {
  136. code: 0,
  137. data: {
  138. name: 'vben',
  139. },
  140. },
  141. },
  142. {
  143. url: '/api/text',
  144. method: 'post',
  145. rawResponse: async (req, res) => {
  146. let reqbody = ''
  147. await new Promise((resolve) => {
  148. req.on('data', (chunk) => {
  149. reqbody += chunk
  150. })
  151. req.on('end', () => resolve(undefined))
  152. })
  153. res.setHeader('Content-Type', 'text/plain')
  154. res.statusCode = 200
  155. res.end(`hello, ${reqbody}`)
  156. },
  157. },
  158. ] as MockMethod[]
  159. ```
  160. ### MockMethod
  161. ```ts
  162. {
  163. // request url
  164. url: string;
  165. // request method
  166. method?: MethodType;
  167. // Request time in milliseconds
  168. timeout?: number;
  169. // default: 200
  170. statusCode?:number;
  171. // response data (JSON)
  172. response?: ((opt: { [key: string]: string; body: Record<string,any>; query: Record<string,any>, headers: Record<string, any>; }) => any) | any;
  173. // response (non-JSON)
  174. rawResponse?: (req: IncomingMessage, res: ServerResponse) => void;
  175. }
  176. ```
  177. ### Example (2.0.0 recommended)
  178. Create the `mockProdServer.ts` file
  179. ```ts
  180. // mockProdServer.ts
  181. import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer'
  182. // Import your mock .ts files one by one
  183. // If you use vite.mock.config.ts, just import the file directly
  184. // You can use the import.meta.glob function to import all
  185. import testModule from '../mock/test'
  186. export function setupProdMockServer() {
  187. createProdMockServer([...testModule])
  188. }
  189. ```
  190. Config `vite-plugin-mock`
  191. ```ts
  192. import { viteMockServe } from 'vite-plugin-mock'
  193. import { UserConfigExport, ConfigEnv } from 'vite'
  194. export default ({ command }: ConfigEnv): UserConfigExport => {
  195. // According to the project configuration. Can be configured in the .env file
  196. let prodMock = true
  197. return {
  198. plugins: [
  199. viteMockServe({
  200. mockPath: 'mock',
  201. localEnabled: command === 'serve',
  202. prodEnabled: command !== 'serve' && prodMock,
  203. injectCode: `
  204. import { setupProdMockServer } from './mockProdServer';
  205. setupProdMockServer();
  206. `,
  207. }),
  208. ],
  209. }
  210. }
  211. ```
  212. ## Sample project
  213. [Vben Admin](https://github.com/anncwb/vue-vben-admin)
  214. ## Note
  215. - The node module cannot be used in the mock .ts file, otherwise the production environment will fail
  216. - 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.
  217. ## License
  218. MIT
  219. [npm-img]: https://img.shields.io/npm/v/vite-plugin-mock.svg
  220. [npm-url]: https://npmjs.com/package/vite-plugin-mock
  221. [node-img]: https://img.shields.io/node/v/vite-plugin-mock.svg
  222. [node-url]: https://nodejs.org/en/about/releases/