个人博客系统(十一、前端-简短的配置)

一、vite.config.ts配置

1. 完整配置

typescript 复制代码
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import * as path from 'node:path'

// https://vite.dev/config/
// command 构建命令, mode 环境
export default defineConfig(({ mode }) => {
  // 加载当前环境
  let env = loadEnv(mode, process.cwd()) //加载环境配置
  let replaceReg = new RegExp(`^${env.VITE_BASE_API}`)
  return {
    plugins: [vue()],
    resolve: {
      alias: {
        '@': path.resolve(process.cwd(), './src'),
      },
    },
    base: env.VITE_NODE_ENV === 'production' ? '' : '/',
    server: {
      port: 8000,
      proxy: {
        [env.VITE_BASE_API]: {
          target: env.VITE_SERVER,
          changeOrigin: true, //支持跨域
          rewrite: (path) => path.replace(replaceReg, ''),
        },
      },
    },
    build: {
      // 构建输出目录
      outDir: 'dist',
      // 静态资源目录
      assetsDir: 'assets',
    },
  }
})

2. 配置讲解

  1. resolve.alias 配置@别名
  2. server配置服务启动端口,proxy配置后端服务
  3. build配置构建参数
  4. 注意rewrite配置,env.VITE_API为自己的环境配置,按照博主的配置该变量为/api_v1,所以前端发送请求的时候需要带上/api_v1/xxxx,xxx为后端接口路径,这样发送请求后又因为replace而实际传递给后端的路径为/xxx,也就是说后端得有接口/xxx而不是/api_v1/xxxx。

二、环境配置

新增两个环境配置文件,文件与src目录同级,需要注意的是环境变量需要以VITE_开头,不然在使用import.meta.env.xxxx的时候会出现无法使用的情况

.env.development

typescript 复制代码
VITE_NODE_ENV="development"
VITE_SERVER="http://localhost:8080"
VITE_BASE_API="/api_v1"

.env.production

typescript 复制代码
VITE_NODE_ENV="production"
VITE_SERVER="http://xxx"
VITE_BASE_API="/api_v1"

三、tsconfig.json配置

1. 完整配置

json 复制代码
{
  "files": [],
  "references": [
    { "path": "./tsconfig.app.json" },
    { "path": "./tsconfig.node.json" }
  ],
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

2. 配置讲解

配置别名主要为了解决webstorm等idel出现别名报错的情况

四、axios配置

1. 安装axios

shell 复制代码
pnpm add axios

2. src目录下新建目录utils

3. utils目录下新建文件requests.ts

4. requests.ts配置

typescript 复制代码
import axios from 'axios'

const requests = axios.create({
    baseURL: import.meta.env.VITE_BASE_API,
    timeout: 180000,
})
//请求拦截器
requests.interceptors.request.use((config) => {
  return config
})

//响应拦截器
requests.interceptors.response.use((response) => {
  return response.data
})

export default requests

这里的baseURL会在发送请求的时候默认追加到host上,即前端发送的请求给/xxx,实际发送的请求为/api_v1/xxx,

其中/api_v1即为博主配置的环境变量VITE_BASE_API的值

相关推荐
我是苏苏18 分钟前
Web开发:C#通过ProcessStartInfo动态调用执行Python脚本
java·服务器·前端
无羡仙38 分钟前
Vue插槽
前端·vue.js
用户6387994773051 小时前
每组件(Per-Component)与集中式(Centralized)i18n
前端·javascript
SsunmdayKT1 小时前
React + Ts eslint配置
前端
开始学java1 小时前
useEffect 空依赖 + 定时器 = 闭包陷阱?count 永远停在 1 的坑我踩透了
前端
zerosrat1 小时前
从零实现 React Native(2): 跨平台支持
前端·react native
狗哥哥2 小时前
🔥 Vue 3 项目深度优化之旅:从 787KB 到极致性能
前端·vue.js
青莲8432 小时前
RecyclerView 完全指南
android·前端·面试
青莲8432 小时前
Android WebView 混合开发完整指南
android·前端·面试
GIS之路2 小时前
GDAL 实现矢量数据转换处理(全)
前端