vite.config.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { defineConfig,loadEnv } from 'vite'
  2. import vue from '@vitejs/plugin-vue'
  3. import replace from '@rollup/plugin-replace'
  4. import config from "./src/config.json";
  5. import path from 'path'
  6. // https://vite.dev/config/
  7. export default ({mode, command})=> {
  8. const env = loadEnv(mode, process.cwd(), 'API_') as Record<
  9. 'API_HOST',
  10. string
  11. >
  12. return defineConfig({
  13. // 插件配置,这里使用了Vue插件,以便支持Vue项目的构建
  14. plugins: [
  15. vue(),
  16. /* 替换字符串 */
  17. replace({
  18. preventAssignment: true,
  19. __API__: `${command === 'build' ? env.API_HOST : ''}`,
  20. }),
  21. ],
  22. base: './', // 确保相对路径正确
  23. build: {
  24. outDir: 'dist',
  25. assetsDir: 'assets',
  26. },
  27. /**
  28. * 配置对象,用于定义 CSS 预处理器的选项。
  29. * 通过此配置可以预导入公共样式文件,确保全局样式在所有 SCSS 文件中可用。
  30. */
  31. css: {
  32. preprocessorOptions: {
  33. scss: {
  34. additionalData: `
  35. @use '@/styles/color.scss' as *;
  36. @use '@/styles/index.scss' as *;
  37. ` // 可选:预导入公共样式
  38. }
  39. }
  40. },
  41. // 解析配置,用于配置模块查找和解析行为
  42. resolve: {
  43. // 定义解析文件的扩展名,这允许导入这些文件时省略扩展名
  44. extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
  45. // 路径别名配置,这里定义了'@'符号指向项目的src目录
  46. // 这有助于减少路径引用的复杂性,提高代码的可读性和可维护性
  47. alias: {
  48. '@': path.resolve(__dirname, './src'),
  49. vue: 'vue/dist/vue.esm-bundler.js' // 使用带 compiler 的构建版本
  50. },
  51. },
  52. // 配置服务器相关设置
  53. server: {
  54. // 设置服务器监听的端口
  55. port: 3000,
  56. // 配置代理设置,用于开发环境中代理API请求
  57. proxy: {
  58. // 当请求以'/api'开头时,将其代理到目标服务器
  59. '/api': {
  60. // 目标服务器的地址
  61. target: config.api,
  62. // 允许更改目标服务器的来源
  63. changeOrigin: true
  64. },
  65. },
  66. },
  67. })
  68. }