1. Install dependencies

npm install mockjs -S
npm install vite-plugin-mock
Copy the code

2. Configuration vite. Config. Js

  • Be aware of the supportTs configuration, which is important to determine whether you are listening for TS or JS
  • Another is to turn on the watchFiles folder listener so that mock changes don’t require a compilation restart
import { defineConfig } from 'vite'
/ / mock services
import { viteMockServe } from 'vite-plugin-mock'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

const localEnabled: boolean = (process.env.USE_MOCK as unknown as boolean) | |false;
const prodEnabled: boolean = (process.env.USE_CHUNK_MOCK as unknown as boolean) | |false;

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), vueJsx(),
  viteMockServe({
    // ↓ Parse the mock folder in the root directory
    mockPath: "mock".localEnabled: localEnabled,  // Develop the package switch
    prodEnabled: prodEnabled, // Make packing switch
    supportTs: true.// When opened, the ts file module can be read. Note that.js files cannot be monitored when opened.
    watchFiles: true.// Monitor file changes})].resolve: {
    alias: {
      '@ /': new URL('./src/'.import.meta.url).pathname
    }
  }
})
Copy the code

3. Add mock files

Create the mock folder in the root directory and add the index.ts file

  • You can simply use your own returned data without introducing MockJS
  • Be sure to reference MockJS if you use a return from MockJS
import { MockMethod } from 'vite-plugin-mock'
const Mock = require('mockjs')
export default[{url: '/api/getUserInfo'.method: 'post'.response: ({ query }) = > {
            return {
                code: 200.data: {
                    nickname: '@cname'.age: '@integer(10-100)'.uid: '@id'.url: '@image'.city: '@city'.country: '@county(true)'.province: '@province'.mobile_phone: '@phone'.email: '@email'.region: '@region'.menus: [{menu_name: 'First order navigation'.id: '@id'.code: 'Nav1'.children: [{code: 'about'.menu_url: 'views/about'.access_permissions: '["about"]'.children: [].menu_name: Test '1'.id: '@id'
                                },
                                {
                                    code: 'home'.menu_url: 'views/home'.access_permissions: '["home"]'.children: [].menu_name: 'test 2'.id: '@id'}]},]},}},},]as MockMethod[]
Copy the code
  1. use
import instance from '@/config/axios.config'
// This is an export API
const getUserInfo = (param? :object) = > instance.post('/api/getUserInfo', param)
getUserInfo()
    .then((res) = > {
        console.log('Request success data', res.data)
    })
    .catch((err) = > {
        console.log('Request failed data', err)
    })
Copy the code
  • Returns the result
{
    "code": 200."data": {
        "nickname": "Yin Yan"."age": 749332707862558."uid": "220000197004097771"."url": "http://dummyimage.com/336x280"."city": "Daqing city"."country": "Overseas overseas -"."province": "Shandong Province"."mobile_phone": "@phone"."email": "[email protected]"."region": "Southwest"."menus": [{"menu_name": "First order navigation"."id": "120000199708273556"."code": "Nav1"."children": [{"code": "about"."menu_url": "views/about"."access_permissions": "[\"about\"]"."children": []."menu_name": 1 "test"."id": "340000198406295422"
                    },
                    {
                        "code": "home"."menu_url": "views/home"."access_permissions": "[\"home\"]"."children": []."menu_name": "The test 2"."id": "410000198406179139"}]}}Copy the code

5. Encountered pits

  1. Because the default value of process.env.vite_use_mock is not true, it needs to be handled. There are two options
  • The first: need to installnpm install cross-env -DThen change the package command to "dev": "cross-env USE_MOCK=true vite",
  • Second: add the ·.env.development· file to the root directory and write to it
# Whether to open mock
VITE_USE_MOCK = true 
Copy the code
  1. I wanted to sneak in the mock module and use it in mock/index.tsimport.meta.globEager('./modules/*.ts')It was found that an error was reported

It was found that the viet-plugin-mock used ES2015 and caused incompatibility