安装axios
cnpm install axios --save
项目根目录新建以下配置文件
开发环境
VITE_APP_BASE_API=http://localhost:3000/api
生产环境
VITE_APP_BASE_API=http://production/api
测试环境
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",
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) => {
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);
});
});
};
export const get = (url: string, params?: any, headers?: any): Promise<any> => {
return request("get", url, undefined, headers, params);
};
export const post = (url: string, data?: any, headers?: any): Promise<any> => {
return request("post", url, data, headers);
};
新建api请求文件
import { get, post } from "@/utils/request";
export const getUserInfo = (params: any) => {
return get("/user/info", { params });
};
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]",
},
},
},