2025-03-29 14:35:49 +08:00

1.3 KiB
Executable File

vite

配置 @ 路径别名

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

环境变量挂载到全局

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

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

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

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

判断当前是否开发环境

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

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

vite.config.js

import { defineConfig } from 'vite';

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