可以不使用 vite-plugin-mock 只引入 mockjs,但是只使用 mockjs 的话配置会繁琐;vite-plugin-mock 做了将 mockjs 集成到 vite 的工作。
package.json
yarn add -D mockjs vite-plugin-mock
.env
VITE_MOCK_ENABLED=true
vite.config.js
import { loadEnv, defineConfig } from 'vite'; import { viteMockServe } from 'vite-plugin-mock'; export default ({ mode }) => { const ENV = loadEnv(mode, process.cwd()); const MOCK_ENABLED = loadEnv(mode, process.cwd()).VITE_MOCK_ENABLED == 'true'; return defineConfig({ plugins: [ viteMockServe({ mockPath: 'src/mock', enable: MOCK_ENABLED, }), ], }); };
src/api/*.js
import request from '@/utils/request'; export default { 列表: (params) => request({ url: '/api/list', method: 'get', params, }), }
src/mock/*.js
export default [ { url: '/api/list', method: 'get', response: (params) => { return {/* 响应数据写这里 */} }, } ]