vite.config.ts 2.84 KB
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { fileURLToPath, URL } from 'node:url';
import fs from 'node:fs';
import path from 'node:path';

/**
 * 数据产物体检。
 *
 * 出险数据集(public/data/*.json)不内置、被 .gitignore 忽略,必须由用户通过顶栏
 * 「导入数据」导入(或本地 `pnpm data:build` 生成)。因此「没有离线产物」是常态、
 * 不是故障,dev server 启动只做信息提示,不再告警去跑 data:build。
 *
 * 行政区边界是另一回事:它作为常驻静态资源 `public/geo/shenzhen.geojson` 随构建走,
 * 这里顺带确认它在,缺了才会告警(那说明构建没带上底图资源)。
 */
function dataReadinessPlugin(root: string) {
  const DATA_DIR = path.resolve(root, 'public/data');
  const GEO = path.resolve(root, 'public/geo/shenzhen.geojson');
  return {
    name: 'data-readiness',
    configureServer(server: any) {
      if (!fs.existsSync(GEO)) {
        server.config.logger.warn(
          `\n  [data] 缺少底图资源 public/geo/shenzhen.geojson,区界聚焦将不可用。\n`,
        );
      }
      if (!fs.existsSync(path.join(DATA_DIR, 'incidents.json'))) {
        server.config.logger.info(
          '  [data] 未内置出险数据 · 请通过顶栏「导入数据」选择本地 xlsx / csv 导入',
          { timestamp: true },
        );
      } else {
        const st = fs.statSync(path.join(DATA_DIR, 'incidents.json'));
        server.config.logger.info(
          `  [data] 已就绪 · incidents.json ${(st.size / 1024 / 1024).toFixed(2)} MB`,
          { timestamp: true },
        );
      }
    },
  };
}

export default defineConfig({
  plugins: [react(), dataReadinessPlugin(process.cwd())],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
      // 组件库源码直引:即使 workspace 软链异常,dev / 构建也能解析
      '@hm/ui': fileURLToPath(new URL('./packages/ui/src/index.ts', import.meta.url)),
      // 自绘图层内核同样源码直引:它没有构建产物,改一行就该在 dev 里立刻看见
      '@hm/map-overlay': fileURLToPath(
        new URL('./packages/map-overlay/src/index.ts', import.meta.url),
      ),
    },
  },
  server: {
    // 监听全部网卡:演示时需要挂到局域网大屏 / 别人机器上跑
    host: '0.0.0.0',
    // 与 uj-store 的 5173 错开,两个项目可同时起
    port: 5174,
    strictPort: false,
  },
  build: {
    // 高德 JS API 是外链 script,不进 bundle;但 react/antd 体积可观,拆开便于并行下载
    rollupOptions: {
      output: {
        manualChunks: {
          react: ['react', 'react-dom', 'react-router-dom'],
          antd: ['antd', '@ant-design/icons'],
        },
      },
    },
    chunkSizeWarningLimit: 1200,
  },
  worker: {
    format: 'es',
  },
});