vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vite mock服务器

Vite中自制mock服务器(不使用第三方服务)

作者:陈楠112

本文主要介绍了Vite中自制mock服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

为什么要 mock

起步

本篇文章会使用到 swraxiosvite-plugin-mock,请自行安装

配置 vite进入 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()
  ],
}))

创建 mock 数据

mkdir mock/ && touch mock/test.ts
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>
  )
}

判断是否在开发环境

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' // 它会写在 window.isDev = true / false
+ },
  plugins: [
    react(),
    viteMockServe()
  ],
}))

封装请求

这里只是简单的封装一下 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>
  )
}

到此这篇关于Vite中自制mock服务器(不使用第三方服务)的文章就介绍到这了,更多相关Vite mock服务器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文