Vite 中文文档 Vite 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • vite

    • 指引
    • 为什么选 Vite
    • 开始
    • 功能
    • 命令行界面
    • 使用插件
    • 依赖预构建
    • 静态资源处理
    • 构建生产版本
    • 部署静态站点
    • 环境变量和模式
    • 服务端渲染
    • 后端集成
    • 与其他工具比较
    • 故障排除
    • 从 v3 迁移
  • API

  • 配置参考

  • vite

  • API

  • 配置参考

vite-plugin-mock


English| 中文

Provide local and prod mocks for vite.

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

Install (yarn or npm)


node version:>=12.0.0

vite version:>=2.0.0

  1. ``` shell
  2. yarn add mockjs
  3. # or
  4. npm i  mockjs -S
  5. ```

  1. ``` shell
  2. yarn add vite-plugin-mock -D
  3. # or
  4. npm i vite-plugin-mock -D
  5. ```

Example


Run Example

  1. ``` shell
  2. # ts example
  3. cd ./examples/ts-examples

  4. yarn install

  5. yarn serve

  6. # js example

  7. cd ./examples/js-examples

  8. yarn install

  9. yarn serve
  10. ```

Usage


Development environment

The development environment is implemented using Connect middleware。

Different from the production environment, you can view the network request record in the Google Chrome console

Config plugin in vite.config.ts

  1. ``` ts
  2. import { UserConfigExport, ConfigEnv } from 'vite'

  3. import { viteMockServe } from 'vite-plugin-mock'
  4. import vue from '@vitejs/plugin-vue'

  5. export default ({ command }: ConfigEnv): UserConfigExport => {
  6.   return {
  7.     plugins: [
  8.       vue(),
  9.       viteMockServe({
  10.         // default
  11.         mockPath: 'mock',
  12.         localEnabled: command === 'serve',
  13.       }),
  14.     ],
  15.   }
  16. }
  17. ```

viteMockServe Options

  1. ``` ts
  2. {
  3.     mockPath?: string;
  4.     supportTs?: boolean;
  5.     ignore?: RegExp | ((fileName: string) => boolean);
  6.     watchFiles?: boolean;
  7.     localEnabled?: boolean;
  8.     ignoreFiles?: string[];
  9.     configPath?: string;
  10.     prodEnabled?: boolean;
  11.     injectFile?: string;
  12.     injectCode?: string;
  13. }
  14. ```

Options


mockPath


type:string

default:'mock'

Set the folder where the mock .ts file is stored

If watchFiles:true, the file changes in the folder will be monitored. And synchronize to the request result in real time

If configPath has a value, it is invalid

supportTs


type:boolean

default:true

After opening, the ts file module can be read. Note that you will not be able to monitor .js files after opening.

ignore


type:RegExp | ((fileName: string) => boolean);

default:undefined

When automatically reading analog .ts files, ignore files in the specified format

watchFiles


type:boolean

default:true

Set whether to monitor changes in mock .ts files

localEnabled


type:boolean

default:command === 'serve'

Set whether to enable the local mock .ts file, do not open it in the production environment

prodEnabled


type:boolean

default:command !=='serve'

Set whether to enable mock function for packaging

injectCode


type:string

default:''

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}

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.

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

injectFile


type:string

default:path.resolve(process.cwd(),'src/main.{ts,js}')

The file injected by injectCode code, the default is src/main.{ts,js} in the project root directory

configPath


type:string

default:vite.mock.config.ts

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

logger


type:boolean

default:true

Whether to display the request log on the console

Mock file example


/path/mock

  1. ``` ts
  2. // test.ts

  3. import { MockMethod } from 'vite-plugin-mock'
  4. export default [
  5.   {
  6.     url: '/api/get',
  7.     method: 'get',
  8.     response: ({ query }) => {
  9.       return {
  10.         code: 0,
  11.         data: {
  12.           name: 'vben',
  13.         },
  14.       }
  15.     },
  16.   },
  17.   {
  18.     url: '/api/post',
  19.     method: 'post',
  20.     timeout: 2000,
  21.     response: {
  22.       code: 0,
  23.       data: {
  24.         name: 'vben',
  25.       },
  26.     },
  27.   },
  28.   {
  29.     url: '/api/text',
  30.     method: 'post',
  31.     rawResponse: async (req, res) => {
  32.       let reqbody = ''
  33.       await new Promise((resolve) => {
  34.         req.on('data', (chunk) => {
  35.           reqbody += chunk
  36.         })
  37.         req.on('end', () => resolve(undefined))
  38.       })
  39.       res.setHeader('Content-Type', 'text/plain')
  40.       res.statusCode = 200
  41.       res.end(`hello, ${reqbody}`)
  42.     },
  43.   },
  44. ] as MockMethod[]
  45. ```

MockMethod


  1. ``` ts
  2. {
  3.   // request url
  4.   url: string;
  5.   // request method
  6.   method?: MethodType;
  7.   // Request time in milliseconds
  8.   timeout?: number;
  9.   // default: 200
  10.   statusCode?:number;
  11.   // response data (JSON)
  12.   response?: ((opt: { [key: string]: string; body: Record<string,any>; query:  Record<string,any>, headers: Record<string, any>; }) => any) | any;
  13.   // response (non-JSON)
  14.   rawResponse?: (req: IncomingMessage, res: ServerResponse) => void;
  15. }
  16. ```

Example (2.0.0 recommended)


Create the mockProdServer.ts file

  1. ``` ts
  2. //  mockProdServer.ts

  3. import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer'

  4. // Import your mock .ts files one by one
  5. // If you use vite.mock.config.ts, just import the file directly
  6. // You can use the import.meta.glob function to import all
  7. import testModule from '../mock/test'

  8. export function setupProdMockServer() {
  9.   createProdMockServer([...testModule])
  10. }
  11. ```

Config vite-plugin-mock

  1. ``` ts
  2. import { viteMockServe } from 'vite-plugin-mock'

  3. import { UserConfigExport, ConfigEnv } from 'vite'

  4. export default ({ command }: ConfigEnv): UserConfigExport => {
  5.   // According to the project configuration. Can be configured in the .env file
  6.   let prodMock = true
  7.   return {
  8.     plugins: [
  9.       viteMockServe({
  10.         mockPath: 'mock',
  11.         localEnabled: command === 'serve',
  12.         prodEnabled: command !== 'serve' && prodMock,
  13.         injectCode: `
  14.           import { setupProdMockServer } from './mockProdServer';
  15.           setupProdMockServer();
  16.         `,
  17.       }),
  18.     ],
  19.   }
  20. }
  21. ```

Sample project


Vben Admin

Note


The node module cannot be used in the mock .ts file, otherwise the production environment will fail
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.

License


MIT
Last Updated: 2023-05-23 11:11:51