Skip to content

vite

配置 @ 路径别名

json
// tsconfig.json
{
  "baseUrl": ".",
  "paths": {
      "@/*": ["src/*"],
    }
}
bash
# 安装node的描述包
pnpm add @types/node
# 安装path
pnpm add path
ts
// vite.config.ts
import { resolve } from 'path'
export default defineConfig({
  base: "./",
  resolve: {
    alias: [
      {
        find: "@",
        replacement: resolve(__dirname, "./src")
      }
    ]
  },
})

环境变量挂载到全局

使用场景: api前缀添加到全局, 所有组件都可以直接使用

  1. 环境文件:
ts
// .env
VITE_API_URL=https://xxx/api
  1. 挂载到全局window上:
tsx
// main.tsx
window.apiUrl = import.meta.env.VITE_API_URL
  1. 添加ts类型:
ts
// vite-env.d.ts
// 第一行引入 Vite 中的客户端类型定义文件

/// <reference types="vite/client" />

interface Window {
  apiUrl: string;
}
  1. 使用:
ts
axios.get(`${window.apiUrl}/students`)

判断当前是否开发环境

ts
  if (import.meta.env.DEV) {
    // 当前是开发环境
  } else {
    // 当前不是开发环境
    iconpath = '/dist/trayIcon.png'
  }

打包时导入路径使用相对路径

vite.config.js

javascript
import { defineConfig } from 'vite';

export default defineConfig({
  base: '', // 将 base 选项设置为空字符串
  // 其他配置选项...
});