【Vite+Ts+Vue3】项目多环境打包配置+axios+Api封装

安装axios

cnpm install axios --save

项目根目录新建以下配置文件

开发环境
// .env.development
VITE_APP_BASE_API=http://localhost:3000/api

生产环境
// .env.production
VITE_APP_BASE_API=http://production/api

测试环境
// .env.test
VITE_APP_BASE_API=http://test.com/api

package.json配置

"dev": "vite",
"dev:test": "vite --mode test", // 测试
"dev:prod": "vite --mode production", // 生产
"build": "vue-tsc && vite build",
"build:test": "vite build --mode test", // 测试
"build:prod": "vite build --mode production", // 生产

vite.config.ts配置api代理

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

export default defineConfig({
  plugins: [vue()],
  define: {
    "process.env": process.env,
  },
  server: {
    proxy: {
      "/api": {
        target: process.env.VITE_APP_BASE_API, // 读取配置变量
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
});

axios配置路径

const instance = axios.create({
  baseURL: "/api", // 代理api
  timeout: 10000,
});

封装axios请求

新建文件:
request.ts
import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
const instance = axios.create({
  baseURL: "/api",
  timeout: 10000, // 请求超时时间
});
// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // config.headers['Authorization'] = `Bearer ${getToken()}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse): any => {
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 封装请求方法
const request = (
  method: string,
  url: string,
  data?: any,
  headers?: any,
  params?: any
): Promise<any> => {
  return new Promise((resolve, reject) => {
    instance
      .request({
        method,
        url,
        data,
        headers,
        params,
      })
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);
      });
  });
};
// 封装 GET 方法
export const get = (url: string, params?: any, headers?: any): Promise<any> => {
  return request("get", url, undefined, headers, params);
};
// 封装 POST 方法
export const post = (url: string, data?: any, headers?: any): Promise<any> => {
  return request("post", url, data, headers);
};

新建api请求文件

// api/index.ts
import { get, post } from "@/utils/request";

// GET 请求示例
export const getUserInfo = (params: any) => {
  return get("/user/info", { params });
};

// POST 请求示例
export const login = (data: any) => {
  return post("/auth/login", data);
};

页面使用

import { getUserInfo } from '@/api/index.ts'
getUserInfo(parmes).then(res=>{

})

打包区分文件类型+hash值相关配置

vite.config.ts文件

build: {
  outDir: "dist",
  assetsDir: "assets",
  sourcemap: false,
  terserOptions: {
    compress: {
      drop_console: true,
      drop_debugger: true,
    },
  },
  // 主要代码
  rollupOptions: {
    output: {
      chunkFileNames: "static/js/[name]-[hash].js",
      entryFileNames: "static/js/[name]-[hash].js",
      assetFileNames: "static/[ext]/[name]-[hash].[ext]",
    },
  },
},

你可能感兴趣的:(Vue.js,前端,js,前端,vue.js,typescript)