Skip to content

Vite 配置详解

前端构建工具配置、图片处理、代理等实用配置

代理配置

解决开发环境跨域问题:

javascript
// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      },
      '/ws': {
        target: 'ws://localhost:8080',
        ws: true
      }
    }
  }
})

路径别名

javascript
import { defineConfig } from 'vite'
import path from 'path'

export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '#': path.resolve(__dirname, 'components'),
      '$': path.resolve(__dirname, 'assets')
    }
  }
})

使用:

javascript
import Home from '@/views/Home.vue'
import Button from '#/Button.vue'

图片资源处理

javascript
export default defineConfig({
  assetsInclude: ['**/*.jpg', '**/*.jpeg', '**/*.png', '**/*.gif', '**/*.svg', '**/*.webp']
})
javascript
// 导入图片(推荐,自动处理 hash)
import imgUrl from './img/logo.png'

function App() {
  return <img src={imgUrl} alt="logo" />
}

// 大的图片可以放 public 目录
<img src="/images/banner.png" alt="banner" />
javascript
// 动态导入图片
const getImage = (name) => new URL(`./images/${name}.png`, import.meta.url).href

环境变量

bash
# .env.development - 开发环境
VITE_API_URL=http://localhost:8080/api
VITE_UPLOAD_URL=http://localhost:8080/upload
VITE_WS_URL=ws://localhost:8080/ws

# .env.production - 生产环境
VITE_API_URL=https://api.example.com
VITE_UPLOAD_URL=https://api.example.com/upload
VITE_WS_URL=wss://api.example.com/ws
javascript
// 使用环境变量(必须以 VITE_ 开头)
console.log(import.meta.env.VITE_API_URL)

//  类型提示
/// <reference types="vite/client" />
javascript
// env.d.ts
/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_API_URL: string
  readonly VITE_UPLOAD_URL: string
  readonly VITE_WS_URL: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}

构建配置

javascript
export default defineConfig({
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: false,
    minify: 'terser',
    rollupOptions: {
      output: {
        chunkFileNames: 'js/[name]-[hash].js',
        entryFileNames: 'js/[name]-[hash].js',
        assetFileNames: '[ext]/[name]-[hash].[ext]',
        manualChunks: {
          vue: ['vue', 'vue-router', 'pinia'],
          vendor: ['axios', 'lodash']
        }
      }
    }
  }
})

CSS 配置

javascript
export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/styles/variables.scss";`
      },
      less: {
        javascriptEnabled: true
      }
    },
    postcss: {
      plugins: [
        require('autoprefixer')
      ]
    }
  }
})

插件配置

bash
npm install @vitejs/plugin-vue @vitejs/plugin-vue-jsx vite-plugin-svg-icons
javascript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import svgIcons from 'vite-plugin-svg-icons'

export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    svgIcons({
      iconDirs: [path.resolve(__dirname, 'src/icons')],
      symbolId: 'icon-[name]'
    })
  ]
})

完整配置示例

javascript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

export default defineConfig({
  base: './',
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  },
  server: {
    port: 3000,
    open: true,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true
      }
    }
  },
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: false,
    minify: 'terser'
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/styles/variables.scss";`
      }
    }
  },
  assetsInclude: ['**/*.svg']
})

常用命令速查

命令说明
npm run dev启动开发服务器
npm run build构建生产版本
npm run preview预览生产版本