Vite2 配置mockjs
仓库地址 https://github.com/vbenjs/vite-plugin-mock
安装前置依赖
1 2 3
| npm i mockjs -S npm i vite-plugin-mock -D npm i cross-env -D
|
package.json
配置script > dev
1
| "dev": "cross-env NODE_ENV=development vite"
|
vite.config.ts
1 2 3
| import { viteMockServe } from 'vite-plugin-mock'
plugins: [vue(),viteMockServe({mockPath: './mock'})],
|
1
| supportTs: true`是否用了ts,可以根据自己选择`true` or `false`
|
代码
在与node_modules
同级目录建立mock目录
目录下建立mock文件 user.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| import {faker} from '@faker-js/faker' import type {User, loginData} from '../../src/types/user' import type {MockMethod} from "vite-plugin-mock";
const userList: User[] = [ { userId: 0, username: 'admin', passwd: 'any', avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif', instruction: 'I am a super administrator', email: 'admin@test.com', roles: ['admin'] }, { userId: 1, username: 'editor', passwd: 'any', avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif', instruction: 'I am an editor', email: 'editor@test.com', roles: ['editor'] }, ]
const userCount = 100
for (let i = 2; i < userCount; i++) { userList.push({ userId: i, username: 'user_' + faker.random.alphaNumeric(9), passwd: faker.random.alphaNumeric(20), avatar: faker.image.imageUrl(), instruction: faker.lorem.sentence(20), email: faker.internet.email(), roles: ['visitor'] }) }
export const register = () => { return { code: 20000 } }
export const login = (body:loginData) => { const {username, passwd} = body for (const user of userList) { if (user.username === username) { return { code: 20000, data: { accessToken: username + '-token' } } } } return { code: 50004, message: 'Invalid User' } }
export const logout = () => { return { code: 20000 } }
export default [ { url: '/api/user/login', method: 'post', response: ({body}: { body: loginData }) => { return login(body) } } ] as MockMethod[]
|