Installations
npm install @meadmin-cn/vite-plugin-mock
Developer Guide
Typescript
Yes
Module System
CommonJS
Min. Node Version
>=12.0.0
Node Version
16.15.1
NPM Version
8.13.2
Score
52.3
Supply Chain
89.7
Quality
73.4
Maintenance
50
Vulnerability
97.9
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (76.44%)
JavaScript (20.94%)
Shell (2.62%)
validate.email 🚀
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Developer
meadmin-cn
Download Statistics
Total Downloads
1,206
Last Day
10
Last Week
36
Last Month
113
Last Year
373
GitHub Statistics
MIT License
98 Commits
1 Branches
Updated on Sep 23, 2022
Bundle Size
162.08 kB
Minified
53.24 kB
Minified + Gzipped
Package Meta Information
Latest Version
2.9.8
Package Id
@meadmin-cn/vite-plugin-mock@2.9.8
Unpacked Size
41.79 kB
Size
10.78 kB
File Count
9
NPM Version
8.13.2
Node Version
16.15.1
Total Downloads
Cumulative downloads
Total Downloads
1,206
Last Day
42.9%
10
Compared to previous day
Last Week
-20%
36
Compared to previous week
Last Month
222.9%
113
Compared to previous month
Last Year
-28.5%
373
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
9
Dev Dependencies
23
vite-plugin-mock
English | ä¸æ–‡
The package forked from [vbenjs/vite - plugin - mock] (https://github.com/vbenjs/vite-plugin-mock), because vbenjs/vite - plugin - mock
stop maintenance, I needed to use its functionality again, so I copied 'vbenjs/vite-plugin-mock' to fix the bug and republish it
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
1yarn add mockjs 2# or 3npm i mockjs -S
1yarn add @meadmin-cn/vite-plugin-mock -D 2# or 3npm i @meadmin-cn/vite-plugin-mock -D
Example
Run Example
1 2# ts example 3cd ./examples/ts-examples 4 5yarn install 6 7yarn serve 8 9# js example 10 11cd ./examples/js-examples 12 13yarn install 14 15yarn serve
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
1import { UserConfigExport, ConfigEnv } from 'vite' 2 3import { viteMockServe } from '@meadmin-cn/vite-plugin-mock' 4import vue from '@vitejs/plugin-vue' 5 6export default ({ command }: ConfigEnv): UserConfigExport => { 7 return { 8 plugins: [ 9 vue(), 10 viteMockServe({ 11 // default 12 mockPath: 'mock', 13 localEnabled: command === 'serve', 14 }), 15 ], 16 } 17}
- viteMockServe Options
1{ 2 mockPath?: string; 3 supportTs?: boolean; 4 ignore?: RegExp | ((fileName: string) => boolean); 5 watchFiles?: boolean; 6 localEnabled?: boolean; 7 ignoreFiles?: string[]; 8 configPath?: string; 9 prodEnabled?: boolean; 10 injectFile?: string; 11 injectCode?: string; 12}
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// test.ts 2 3import { MockMethod } from '@meadmin-cn/vite-plugin-mock' 4export 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[]
MockMethod
1{ 2 // request url 3 url: string; 4 // request method 5 method?: MethodType; 6 // Request time in milliseconds 7 timeout?: number; 8 // default: 200 9 statusCode?:number; 10 // response data (JSON) 11 response?: ((opt: { [key: string]: string; body: Record<string,any>; query: Record<string,any>, headers: Record<string, any>; }) => any) | any; 12 // response (non-JSON) 13 rawResponse?: (req: IncomingMessage, res: ServerResponse) => void; 14} 15
Example (2.0.0 recommended)
Create the mockProdServer.ts
file
1// mockProdServer.ts 2 3import { createProdMockServer } from '@meadmin-cn/vite-plugin-mock/es/createProdMockServer' 4 5// Import your mock .ts files one by one 6// If you use vite.mock.config.ts, just import the file directly 7// You can use the import.meta.glob function to import all 8import testModule from '../mock/test' 9 10export function setupProdMockServer() { 11 createProdMockServer([...testModule]) 12}
Config vite-plugin-mock
1import { viteMockServe } from '@meadmin-cn/vite-plugin-mock' 2 3import { UserConfigExport, ConfigEnv } from 'vite' 4 5export default ({ command }: ConfigEnv): UserConfigExport => { 6 // According to the project configuration. Can be configured in the .env file 7 let prodMock = true 8 return { 9 plugins: [ 10 viteMockServe({ 11 mockPath: 'mock', 12 localEnabled: command === 'serve', 13 prodEnabled: command !== 'serve' && prodMock, 14 injectCode: ` 15 import { setupProdMockServer } from './mockProdServer'; 16 setupProdMockServer(); 17 `, 18 }), 19 ], 20 } 21}
Sample project
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

No vulnerabilities found.

No security vulnerabilities found.