vite2+vue3项目中引入vite-plugin-mock

插件官方地址

  1. 安装vite-plugin-mock
npm i axios mockjs -s
npm i cross-env vite-plugin-mock -D
  1. 新建mock文件夹,存放本地mock文件
// user.js
export default [
  {
    url: '/api/createUser',
    method: 'post',
    response: ({ body }) => {
      return {
        code: 0,
        message: 'ok',
        data: null,
      }
    },
  },
]
  1. src根目录下创建mockProdServer.js文件
import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer'
import userMock from '../mock/user'

export function setupProdMockServer() {
  createProdMockServer([ ...userMock])
}
  1. vite.config.js文件配置
import { viteMockServe } from 'vite-plugin-mock'
import vue from '@vitejs/plugin-vue'

export default ({ command }) => {
  let prodMock = true
  return {
    plugins: [
      vue(),
      viteMockServe({
        // default
        mockPath: 'mock',
        localEnabled: command === 'serve',
        prodEnabled: command !== 'serve' && prodMock,
        injectCode: `
          import { setupProdMockServer } from './mockProdServer';
          setupProdMockServer();
        `,
      }),
    ],
  }
}
  1. 本地mock

删除vite.config.jsviteMockServe配置下的injectCodeprodEnabled选项,或将prodMock = false
main.js中添加

import { setupProdMockServer } from './mockProdServer';
if(import.meta.env === 'development'){
  setupProdMockServer()
}

推荐阅读更多精彩内容