import { defineConfig, loadEnv } from 'vite' import vue from '@vitejs/plugin-vue' import path from 'path' // https://vite.dev/config/ export default defineConfig(({ mode }) => { // 加载对应模式的环境变量 const env = loadEnv(mode, process.cwd()); let config = { plugins: [vue()], resolve: { // 配置别名 alias: { '@': path.resolve(__dirname, 'src'), }, }, css: { preprocessorOptions: { // 配置全局样式 scss: { additionalData: `@import "@/styles/variables.scss";`, }, }, }, }; if (mode === 'development') { // 开发模式下的配置 config = { ...config, server: { host: env.VITE_DEV_HOST || '0.0.0.0', // 允许通过网络访问,从环境变量获取host port: parseInt(env.VITE_DEV_PORT, 10) || 8080, // 自定义端口,从环境变量获取port open: true, // 自动打开浏览器 // 配置代理 proxy: { '/api': { target: env.VITE_DEV_API_URL, changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ''), }, }, }, }; } else if (mode === 'production') { // 生产模式下的配置 config = { ...config, build: { terserOptions: { compress: { drop_console: env.VITE_BUILD_DROP_CONSOLE === 'true', // 移除 console 语句,从环境变量获取是否移除console }, }, // 配置打包输出目录 outDir: 'dist', // 配置资源文件名格式 assetsDir: 'assets', rollupOptions: { output: { // 手动分割代码 manualChunks(id) { if (id.includes('node_modules')) { return id.toString().split('node_modules/')[1].split('/')[0].toString(); } }, }, }, }, }; } return config; })