vite.config.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import {defineConfig, loadEnv} from 'vite'
  2. import path from 'path'
  3. import fs from 'fs'
  4. import createVitePlugins from './vite/plugins'
  5. // https://vitejs.dev/config/
  6. export default defineConfig(({mode, command}) => {
  7. const env = loadEnv(mode, process.cwd())
  8. const {VITE_APP_ENV} = env
  9. const VITE_SERVICE_BASE_TITLE=env.VITE_SERVICE_BASE_TITLE
  10. const VITE_SERVER_URL=env.VITE_SERVER_URL
  11. const mockDir = path.resolve(__dirname, './mock/onemap')
  12. return {
  13. base: env.VITE_APP_BASE_TITLE,
  14. plugins: [
  15. createVitePlugins(env, command === 'build'),
  16. // mock 中间件(仅 development)
  17. {
  18. name: 'vite-plugin-mock-onemap',
  19. configureServer(server) {
  20. server.middlewares.use((req, res, next) => {
  21. if (mode !== 'development') return next()
  22. const url = req.url || ''
  23. const match = url.match(/^\/gw-api\/onemap\/(.+?)(?:\?.*)?$/)
  24. if (!match) return next()
  25. const file = path.join(mockDir, match[1] + '.json')
  26. if (!fs.existsSync(file)) return next()
  27. res.setHeader('Content-Type', 'application/json')
  28. res.end(fs.readFileSync(file, 'utf-8'))
  29. })
  30. }
  31. }
  32. ],
  33. resolve: {
  34. // https://cn.vitejs.dev/config/#resolve-alias
  35. alias: {
  36. // 设置路径
  37. '~': path.resolve(__dirname, './'),
  38. // 设置别名
  39. '@': path.resolve(__dirname, './src')
  40. },
  41. // https://cn.vitejs.dev/config/#resolve-extensions
  42. extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
  43. },
  44. // 打包配置
  45. build: {
  46. // https://vite.dev/config/build-options.html
  47. sourcemap: command === 'build' ? false : 'inline',
  48. outDir: 'dist',
  49. assetsDir: 'assets',
  50. chunkSizeWarningLimit: 2000,
  51. rollupOptions: {
  52. output: {
  53. chunkFileNames: 'static/js/[name]-[hash].js',
  54. entryFileNames: 'static/js/[name]-[hash].js',
  55. assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
  56. }
  57. }
  58. },
  59. // vite 相关配置
  60. server: {
  61. port: env.VITE_APP_PORT,
  62. host: '0.0.0.0',
  63. open: true,
  64. proxy: {
  65. // https://cn.vitejs.dev/config/#server-proxy
  66. [VITE_SERVICE_BASE_TITLE]: {
  67. target: VITE_SERVER_URL,
  68. changeOrigin: true,
  69. rewrite: (path) => path.replace(new RegExp(`^${VITE_SERVICE_BASE_TITLE}`), ''),
  70. },
  71. // springdoc proxy
  72. '^/v3/api-docs/(.*)': {
  73. target: VITE_SERVER_URL,
  74. changeOrigin: true,
  75. }
  76. }
  77. },
  78. css: {
  79. postcss: {
  80. plugins: [
  81. {
  82. postcssPlugin: 'internal:charset-removal',
  83. AtRule: {
  84. charset: (atRule) => {
  85. if (atRule.name === 'charset') {
  86. atRule.remove()
  87. }
  88. }
  89. }
  90. }
  91. ]
  92. }
  93. }
  94. }
  95. })