Vite uses the configuration of the mock plugin (vite-plugin-mock)

    Mock is often used in projects, and configuration is also common, so record it here

1. Installation dependencies

# 使用 npm 安装
npm install mockjs vite-plugin-mock
# 使用 yarn 安装
yarn add mockjs vite-plugin-mock

Two, configuration

1. In the root directory of the project vite.config,ts

import type { ConfigEnv, UserConfig } from 'vite';

import mockPlugin './build/vite/plugin';


export default ({ mode }: ConfigEnv): UserConfig => {

  const VITE_PORT = '8080'
  const VITE_PROXY_URL = 'https://222.222.222.222'
  return {
    plugins: mockPlugin(true/false), //在这个文件里面,可以配置mock的一些属性  true/false代表的是mock开关 
    base: './',
    resolve: {
       ....
    },
    css: {
       .....
    },
    server: {
      port: VITE_PORT,   //端口
      open: '/',
      host: '0.0.0.0',   //本地地址:localhost或者其他
      https: true,
      proxy: {           //代理
        '/iotp': {
          target: VITE_PROXY_URL,    //请求的url,例后端给的地址
          changeOrigin: true,        //当进行代理时,Host 头部的源默认会保持原状;你可以设置 changeOrigin 为 true 来覆盖这种行为;变成target对应得地址
          secure: false,             // 关闭SSL证书校验
          rewrite: path => {         //重定地址,比如:把以/aaa开头的地址换成''
            return path.replace(/^\/aaaa/, '');
          },
        },
      },
    },
    build: {
      rollupOptions: {
        input: {
          main: resolve(process.cwd(), 'index.html'),
        },
      },
    },
  };
};

2. In the ./build/vite/plugin file (here the file is created by yourself)

import type { Plugin } from 'vite';
import { viteMockServe } from 'vite-plugin-mock';

export default function mockPlugin(VITE_USE_MOCK: boolean) {
  return {
    ...viteMockServe({
      mockPath: 'mock',          //mock文件路径,在根路径下创建一个mock文件
      localEnabled: VITE_USE_MOCK, //mock开关
      prodEnabled: false,         //生产环境下为false,这样就不会被打包到生产包中
      ignore: /^\_/,       //忽略开始_路径
    }),
  } as Plugin;
}

3. Create a mock file in the root directory, and subdivide various files below, for example, create an api/login.ts

export default [
  {
    url: "/api/login",
    method: "post",
    response: () => {
      return {
        code: 200,
        message: "ok",
        data: {success:true}
      };
    }
  }
];

4. If it is called externally, it is a normal call, directly

axios.post('/api/login',xxx,xxx)  

Note: axios needs to be packaged internally

5. Additional supplement: the above case is that the mock interface is successful, if you want the mock interface to fail, then in step 3

export default [

{} //Empty object is enough

]

At this time, the interface will return a 401 status code, and you can do follow-up processing on the interface failure. 

6. At this point, a mock is completed

Guess you like

Origin blog.csdn.net/du111_/article/details/127089719