欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vite中自制mock服務(wù)器(不使用第三方服務(wù))

 更新時(shí)間:2023年04月16日 16:22:29   作者:陳楠112  
本文主要介紹了Vite中自制mock服務(wù)器,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

為什么要 mock?

  • 后臺(tái)接口還沒(méi)完成,但前端要用到接口
  • 我想篡改后臺(tái)接口的結(jié)果,測(cè)試一些分支邏輯

起步

本篇文章會(huì)使用到 swr、axiosvite-plugin-mock,請(qǐng)自行安裝

配置 vite進(jìn)入 vite.config.ts,添加以下代碼

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { viteMockServe } from 'vite-plugin-mock'

export default defineConfig(({ command }) => ({
  plugins: [
    react(),
    viteMockServe()
  ],
}))

創(chuàng)建 mock 數(shù)據(jù)

  • 創(chuàng)建 mock/test.ts 文件
mkdir mock/ && touch mock/test.ts
  • 添加 mock 數(shù)據(jù)
import { MockMethod } from 'vite-plugin-mock'
export default [
  {
    url: '/api/v1/me',
    method: 'get',
    response: () => {
      return {
        id: 1,
        name: 'Niki'
      }
    }
  }
] as MockMethod[]

使用 useSWR

在使用到的組件中用:

import useSWR from 'swr'
import axios from 'axios'

export const Home: React.FC = () => {
  const { data, error, isLoading } = useSWR('/api/v1/me', path => {
    return axios.get(path)
  })

  if (isLoading) {
    return <div>加載中...</div>
  }
  if (error) {
    return <div>加載失敗</div>
  }

  return (
    <div>Hi, I am {data.name}!</div>
  )
}

判斷是否在開(kāi)發(fā)環(huán)境

vite.config.ts 里添加

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { viteMockServe } from 'vite-plugin-mock'

// https://vitejs.dev/config/
export default defineConfig(({ command }) => ({
+ define: {
+   isDev: command === 'serve' // 它會(huì)寫(xiě)在 window.isDev = true / false
+ },
  plugins: [
    react(),
    viteMockServe()
  ],
}))

封裝請(qǐng)求

這里只是簡(jiǎn)單的封裝一下 Axios

mkdir src/lib/ touch src/lib/ajax.tsx
import axios from 'axios'

axios.defaults.baseURL = isDev ? '/' : 'xxx' // 'xxx' 改為線上的 ip:端口
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.timeout = 10000

export const ajax = {
  get: (path: `/${string}`) => {
    return axios.get(path)
  }
}

最終使用

import useSWR from 'swr'
import { ajax } from '../lib/ajax'

export const Home: React.FC = () => {
  const { data, error, isLoading } = useSWR('/api/v1/me', path => {
    return ajax.get(path)
  })

  if (isLoading) {
    return <div>加載中...</div>
  }
  if (error) {
    return <div>加載失敗</div>
  }

  return (
    <div>Hi, I am {data.name}!</div>
  )
}

到此這篇關(guān)于Vite中自制mock服務(wù)器(不使用第三方服務(wù))的文章就介紹到這了,更多相關(guān)Vite mock服務(wù)器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論