【Vite+Ts+Vue3+Element Plus】项目多环境打包配置+axios+Api封装+loading判断

19 篇文章 0 订阅

安装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,loadEnv } from "vite"; // 引入loadEnv
import vue from "@vitejs/plugin-vue";

// export default defineConfig({}) 
// 重写更换为:
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  return {
    plugins: [vue()],
    server: {
      host: "0.0.0.0",
      // https: true,
      proxy: {
        "/api": {
          target: env.VITE_APP_BASE_API,  // 使用env的变量
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    }
  };
})

页面如果需要使用env 自行扩展:

define: {
	"process.env": env,
},

axios配置路径

const instance = axios.create({
  baseURL: "/api", // 代理api,直接读取变量
  timeout: 10000,
});

封装axios请求+loading

新建文件:
request.ts
import { ElLoading } from "element-plus";
import { Message } from "@/components/public-fn.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);
  }
);
export const request = (
  options: any,
  loading: boolean = true
): Promise<any> => {
  const loadingInstance =
    options.loading ?? loading
      ? ElLoading.service({
          lock: true,
          fullscreen: true,
        })
      : null;
  const { method, url, data, headers, params } = options;
  return new Promise((resolve, reject) => {
    instance
      .request({
        method,
        url,
        data,
        headers,
        params,
      })
      .then((response: any) => {
        if (response.code && response.code !== 200) {
          Message(response.msg, "error");
        } else {
          resolve(response);
        }
      })
      .catch((error) => {
        Message(error, "error");
        reject(error);
      })
      .finally(() => {
        loadingInstance?.close();
      });
  });
};

新建api请求文件

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

// POST 请求示例
export const webapiPackageConfigApi = (data: any) => {
  return request({
    url: "/webapi_package/config",
    method: "post",
    params: data,
    loading:false, // 当前接口不使用loading
  });
};

页面使用

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]",
      manualChunks(id) {
        if (id.includes("node_modules")) {
          return id
            .toString()
            .split("node_modules/")[1]
            .split("/")[0]
            .toString();
        }
      },
    },
    commonjsOptions: {
      requireReturnsDefault: "namespace",
    },
  },
},

在这里插入图片描述
感谢你的阅读,如对你有帮助请收藏+关注!
只分享干货实战精品从不啰嗦!!!
如某处不对请留言评论,欢迎指正~
博主可收徒、常玩QQ飞车,可一起来玩玩鸭~

  • 27
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cnsv雨

谢谢您的鼓励,我会继续努力的~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值