- 安装
vite-plugin-mock
npm i axios mockjs -s
npm i cross-env vite-plugin-mock -D
- 新建
mock
文件夹,存放本地mock文件
// user.js
export default [
{
url: '/api/createUser',
method: 'post',
response: ({ body }) => {
return {
code: 0,
message: 'ok',
data: null,
}
},
},
]
- 在
src
根目录下创建mockProdServer.js
文件
import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer'
import userMock from '../mock/user'
export function setupProdMockServer() {
createProdMockServer([ ...userMock])
}
-
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();
`,
}),
],
}
}
- 本地mock
删除vite.config.js
中viteMockServe
配置下的injectCode
和prodEnabled
选项,或将prodMock = false
在main.js
中添加
import { setupProdMockServer } from './mockProdServer';
if(import.meta.env === 'development'){
setupProdMockServer()
}