Why do you want itmock
?
- The background interface has not been completed yet, but the front-end needs to use the interface
- I want to tamper with the results of the background interface and test some branch logic
Get started
This article will be usedswr
、axios
、vite-plugin-mock
, please install it yourself
Configurationvite
Enter, add the following code
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { viteMockServe } from 'vite-plugin-mock' export default defineConfig(({ command }) => ({ plugins: [ react(), viteMockServe() ], }))
Create mock data
- create
mock/
document
mkdir mock/ && touch mock/
- Add mock data
import { MockMethod } from 'vite-plugin-mock' export default [ { url: '/api/v1/me', method: 'get', response: () => { return { id: 1, name: 'Niki' } } } ] as MockMethod[]
Use useSWR
Use in the components used:
import useSWR from 'swr' import axios from 'axios' export const Home: = () => { const { data, error, isLoading } = useSWR('/api/v1/me', path => { return (path) }) if (isLoading) { return <div>loading...</div> } if (error) { return <div>Loading failed</div> } return ( <div>Hi, I am {}!</div> ) }
Determine whether it is in the development environment
existAdded in
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { viteMockServe } from 'vite-plugin-mock' // /config/ export default defineConfig(({ command }) => ({ + define: { + isDev: command === 'serve' // It will be written in = true / false+ }, plugins: [ react(), viteMockServe() ], }))
Encapsulation request
Here is just a simple encapsulation
Axios
mkdir src/lib/ touch src/lib/
import axios from 'axios' = isDev ? '/' : 'xxx' // 'xxx' is changed to the ip:port online['Content-Type'] = 'application/json' = 10000 export const ajax = { get: (path: `/${string}`) => { return (path) } }
Final use
import useSWR from 'swr' import { ajax } from '../lib/ajax' export const Home: = () => { const { data, error, isLoading } = useSWR('/api/v1/me', path => { return (path) }) if (isLoading) { return <div>loading...</div> } if (error) { return <div>Loading failed</div> } return ( <div>Hi, I am {}!</div> ) }
This is the end of this article about homemade mock servers in Vite (not using third-party services). For more related content on Vite mock servers, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!