我们看到官网来进行 Mock 环境的集成:
安装插件
pnpm install -D vite-plugin-mock mockjs
配置 vite.config.ts
import { defineConfig } from 'vite' import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' // 引入 svg 图标所需要的插件 import vue from '@vitejs/plugin-vue' import path from 'path' import {viteMockServe} from "vite-plugin-mock"; // https://vitejs.dev/config/ // command 区分项目所处的环境 export default defineConfig(({ command }) => { return { plugins: [vue(), createSvgIconsPlugin({ iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')], // 图标的存放目录 symbolId: 'icon-[dir]-[name]' }), viteMockServe({ enable: command === 'serve' // 保证项目开发阶段可以使用 mock 接口 }) ], resolve: { alias: { "@": path.resolve("./src") // 相对路径别名配置,使用 @ 代替 src } }, // scss 全局变量的一个配置 css: { preprocessorOptions: { scss: { javascriptEnabled: true, additionalData: '@import "./src/styles/variable/index.scss";' } } } } })
之后在项目根目录创建 mock 文件夹,去创建我们需要的 Mock 数据和对应的接口
这里我们就需要看到官网的制作接口的语法:
Mock file examples
The pattern is an ant-style path pattern string, use @howiefh/ant-path-matcher to match the pattern and request URL.
// example/mock/es.mock.ts import { MockHandler } from '../../src' const mocks: MockHandler[] = [ { pattern: '/api/test1/1', handle: (req, res) => { res.end('Hello world!' + req.url) } }, { pattern: '/api/test1/*', handle: (req, res) => { res.end('Hello world!' + req.url) } }, { pattern: '/api/test1/users/{userId}', handle: (req, res) => { const data = { url: req.url, params: req.params, query: req.query, body: req.body } res.setHeader('Content-Type', 'application/json') res.end(JSON.stringify(data)) } }, { pattern: '/api/test1/body/json', method: 'POST', handle: (req, res) => { res.setHeader('Content-Type', 'application/json') //req is incomingMessage which extends stream.Readable // --> https://nodejs.org/api/stream.html#readablereadsize // res.end need to be within the function // there is a size limit for the bodyString to get parsed req.on('data', (bodyString: string) => { let body: object = JSON.parse(bodyString) res.end(JSON.stringify(body)) }) } }, ] export default mocks // example/mock/apis/es2.mock.ts import { MockHandler } from 'vite-plugin-mock-server' export default (): MockHandler[] => [ { pattern: '/api/test2/1', handle: (req, res) => { res.end('Hello world!' + req.url) } }, { pattern: '/api/test2/2', handle: (req, res) => { res.statusCode = 203 res.end('Hello world!' + req.url) } } ]
// example/mock/cjs.mock.js module.exports = [ { pattern: '/api/merchant1', method: 'GET', handle: (req, res) => { res.end('merchant1:' + req.url) } }, { pattern: '/api/merchant2', method: 'GET', handle: (req, res) => { res.end('merchant2:' + req.url) } }, { pattern: '/api/merchant2', method: 'GET', handle: (req, res) => { res.end('merchant3:' + req.url) } } ] // example/mock/apis/cjs2.mock.js module.exports = [ { pattern: '/api/hello1', method: 'GET', handle: (req, res) => { res.end('hello1:' + req.url) } }, { pattern: '/api/hello2', method: 'GET', handle: (req, res) => { res.end('hello2:' + req.url) } }, { pattern: '/api/hello3', method: 'GET', handle: (req, res) => { res.end('hello2:' + req.url) } } ]
可以看到是十分简单的,无非就是提供数据的函数 + 对外暴露一个数组,数组中包含的便是接口。
这里制作一个用户登录的接口:
const createUserList = () => { return [ { userId: 1, avatar: 'https://pic1.zhimg.com/80/v2-083faf550543c1e9f134b56b3322ee3c_720w.webp', username: 'admin', password: '123456789', desc: '下船不谈船里事', roles: ['平台管理员'], buttons: ['cuser.detail'], routes: ['home'], token: 'Admin Token' }, { userId: 2, avatar: 'https://pic1.zhimg.com/80/v2-e1427f6a21122ac163ff98d24f55d372_720w.webp', username: 'system', password: '123456789', desc: '旧人不谈近况,新人不讲过往', roles: ['系统管理员'], buttons: ['cuser.detail', 'cuser.user'], routes: ['home'], token: 'Admin Token' } ] } export default [ // 用户登录接口 { url: '/api/user/login', method: 'post', response: ({ body }) => { // 获取请求体携带过来的用户名与密码 const { username, password } = body // 调用获取用户信息函数,用于判断是否有此用户 const checkUser = createUserList().find( (item) => item.username === username && item.password === password ) // 没有用户则返回失败信息 if(!checkUser) { return { code: 201, data: { message: '账号或者密码不正确' } } } // 如果有返回成功信息 const { token } = checkUser return { code: 200, data: { token } } } }, // 获取用户信息接口 { url: '/api/user/info', method: 'get', response: (request) => { // 获取请求头携带的 token const token = request.headers.token // 查看用户信息数据中是否包含有此 token 的用户 const checkUser = createUserList().find((item) => item.token === token) // 没有就返回失败信息 if(!checkUser) { return { code: 201, data: { message: '获取用户信息失败' } } } // 有就返回成功信息 return { code: 200, data: { checkUser } } } } ]
测试:
<script setup lang="ts"> import axios from 'axios' import { onMounted } from "vue"; onMounted(() => { // 登录接口 axios({ url: '/api/user/login', method: 'POST', data: { username: 'admin', password: '123456789' } }).then(res => { console.log(res) }) }) </script> <template> </template> <style scoped lang="scss"> </style>