vite+mockjs+vite-plugin-mock 搭建mock环境

1. 安装依赖

npm install mockjs -S
npm install vite-plugin-mock

2. 配置vite.config.js

  • 一定要注意supportTs配置,这个是决定监听的是ts还是js, 很重要
  • 再一个是要将 watchFiles 文件夹监听打开,这样更改mock的时候,不需要重新启动编译
import { defineConfig } from 'vite'
// mock服务
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({
    // ↓解析根目录下的mock文件夹
    mockPath: "mock",
    localEnabled: localEnabled,  // 开发打包开关
    prodEnabled: prodEnabled, // 生产打包开关
    supportTs: true, // 打开后,可以读取 ts 文件模块。 请注意,打开后将无法监视.js 文件。
    watchFiles: true, // 监视文件更改
  })],
  resolve: {
    alias: {
      '@/': new URL('./src/', import.meta.url).pathname
    }
  }
})

3. 添加mock文件

在根目录创建mock文件夹,然后添加index.ts 文件

  • 单纯的使用自己的返回数据话,可以不用引入mockjs
  • 如果是要是使用mockjs的返回的话,一定要引用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: '一级导航',
                            id: '@id',
                            code: 'Nav1',
                            children: [
                                {
                                    code: 'about',
                                    menu_url: 'views/about',
                                    access_permissions: '["about"]',
                                    children: [],
                                    menu_name: '测试1',
                                    id: '@id'
                                },
                                {
                                    code: 'home',
                                    menu_url: 'views/home',
                                    access_permissions: '["home"]',
                                    children: [],
                                    menu_name: '测试2',
                                    id: '@id'
                                }
                            ]
                        },

                    ]
                },
            }
        },
    },
] as MockMethod[]
  1. 使用
import instance from '@/config/axios.config'
// 这是一个导出api 
const getUserInfo = (param?: object) => instance.post('/api/getUserInfo', param)
getUserInfo()
    .then((res) => {
        console.log('请求成功数据', res.data)
    })
    .catch((err) => {
        console.log('请求失败数据', err)
    })
  • 返回结果
{
    "code": 200,
    "data": {
        "nickname": "尹艳",
        "age": 749332707862558,
        "uid": "220000197004097771",
        "url": "http://dummyimage.com/336x280",
        "city": "大庆市",
        "country": "海外 海外 -",
        "province": "山东省",
        "mobile_phone": "@phone",
        "email": "[email protected]",
        "region": "西南",
        "menus": [
            {
                "menu_name": "一级导航",
                "id": "120000199708273556",
                "code": "Nav1",
                "children": [
                    {
                        "code": "about",
                        "menu_url": "views/about",
                        "access_permissions": "[\"about\"]",
                        "children": [],
                        "menu_name": "测试1",
                        "id": "340000198406295422"
                    },
                    {
                        "code": "home",
                        "menu_url": "views/home",
                        "access_permissions": "[\"home\"]",
                        "children": [],
                        "menu_name": "测试2",
                        "id": "410000198406179139"
                    }
                ]
            }
        ]
    }
}

5. 遇到的坑

  1. 应为process.env.VITE_USE_MOCK 的默认值不是true,所以需要处理, 有两种方案
  • 第一种: 需要安装 npm install cross-env -D 然后更改打包命令为 "dev": "cross-env USE_MOCK=true vite",
  • 第二种: 在根目录添加 ·.env.development· 文件, 然后在里面写
# Whether to open mock
VITE_USE_MOCK = true 
  1. 本想在引入mock模块的时候偷个懒的,在mock/index.ts 里面使用import.meta.globEager('./modules/*.ts') 结果发现报错
image.png

发现vite-plugin-mock 用了es2015导致不兼容


image.png

你可能感兴趣的:(vite+mockjs+vite-plugin-mock 搭建mock环境)