vite.config.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { defineConfig } from 'vite';
  2. import react from '@vitejs/plugin-react';
  3. import path from 'path';
  4. import fs from 'fs';
  5. // SSL证书配置
  6. // HTTPS开关:通过环境变量 VITE_ENABLE_HTTPS 控制(true/false)
  7. const enableHttps = process.env.VITE_ENABLE_HTTPS === 'true';
  8. // 优先使用环境变量指定的证书路径(生产环境)
  9. const sslKeyPath = process.env.VITE_SSL_KEYFILE || path.resolve(__dirname, '../ssl/key.pem');
  10. const sslCertPath = process.env.VITE_SSL_CERTFILE || path.resolve(__dirname, '../ssl/cert.pem');
  11. // 根据开关和证书文件决定HTTPS配置
  12. let httpsConfig: any = false;
  13. if (enableHttps) {
  14. if (fs.existsSync(sslKeyPath) && fs.existsSync(sslCertPath)) {
  15. httpsConfig = {
  16. key: fs.readFileSync(sslKeyPath),
  17. cert: fs.readFileSync(sslCertPath),
  18. };
  19. console.log('✅ HTTPS已启用,使用SSL证书:');
  20. console.log(` 证书: ${sslCertPath}`);
  21. console.log(` 私钥: ${sslKeyPath}`);
  22. } else {
  23. console.log('⚠️ HTTPS已启用但SSL证书不存在,以HTTP模式启动');
  24. console.log(` 证书路径: ${sslCertPath}`);
  25. console.log(` 私钥路径: ${sslKeyPath}`);
  26. }
  27. } else {
  28. console.log('ℹ️ HTTPS已禁用(VITE_ENABLE_HTTPS=false),以HTTP模式启动');
  29. }
  30. export default defineConfig({
  31. plugins: [react()],
  32. resolve: {
  33. alias: {
  34. '@': path.resolve(__dirname, './src'),
  35. },
  36. },
  37. server: {
  38. port: 3000,
  39. host: '0.0.0.0', // 允许外部访问
  40. https: httpsConfig,
  41. },
  42. });