vite.config.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import dayjs from "dayjs";
  2. import { resolve } from "path";
  3. import pkg from "./package.json";
  4. import { warpperEnv } from "./build";
  5. import { getPluginsList } from "./build/plugins";
  6. import { include, exclude } from "./build/optimize";
  7. import { UserConfigExport, ConfigEnv, loadEnv } from "vite";
  8. /** 当前执行node命令时文件夹的地址(工作目录) */
  9. const root: string = process.cwd();
  10. /** 路径查找 */
  11. const pathResolve = (dir: string): string => {
  12. return resolve(__dirname, ".", dir);
  13. };
  14. /** 设置别名 */
  15. const alias: Record<string, string> = {
  16. "@": pathResolve("src"),
  17. "@build": pathResolve("build")
  18. };
  19. const { dependencies, devDependencies, name, version } = pkg;
  20. const __APP_INFO__ = {
  21. pkg: { dependencies, devDependencies, name, version },
  22. lastBuildTime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
  23. };
  24. export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  25. const {
  26. VITE_API_SERVER,
  27. VITE_CDN,
  28. VITE_PORT,
  29. VITE_COMPRESSION,
  30. VITE_PUBLIC_PATH
  31. } = warpperEnv(loadEnv(mode, root));
  32. return {
  33. base: VITE_PUBLIC_PATH,
  34. root,
  35. resolve: {
  36. alias
  37. },
  38. // 服务端渲染
  39. server: {
  40. // 端口号
  41. port: VITE_PORT,
  42. host: "0.0.0.0",
  43. // 本地跨域代理 https://cn.vitejs.dev/config/server-options.html#server-proxy
  44. proxy: {
  45. "/api": {
  46. target: VITE_API_SERVER,
  47. changeOrigin: true,
  48. rewrite: path => path.replace(/^\/api/, "")
  49. }
  50. },
  51. // 预热文件以提前转换和缓存结果,降低启动期间的初始页面加载时长并防止转换瀑布
  52. warmup: {
  53. clientFiles: ["./index.html", "./src/{views,components}/*"]
  54. }
  55. },
  56. plugins: getPluginsList(command, VITE_CDN, VITE_COMPRESSION),
  57. // https://cn.vitejs.dev/config/dep-optimization-options.html#dep-optimization-options
  58. optimizeDeps: {
  59. include,
  60. exclude
  61. },
  62. build: {
  63. sourcemap: false,
  64. // 消除打包大小超过500kb警告
  65. chunkSizeWarningLimit: 4000,
  66. rollupOptions: {
  67. input: {
  68. index: pathResolve("index.html")
  69. },
  70. // 静态资源分类打包
  71. output: {
  72. chunkFileNames: "static/js/[name]-[hash].js",
  73. entryFileNames: "static/js/[name]-[hash].js",
  74. assetFileNames: "static/[ext]/[name]-[hash].[ext]"
  75. }
  76. }
  77. },
  78. define: {
  79. __INTLIFY_PROD_DEVTOOLS__: false,
  80. __APP_INFO__: JSON.stringify(__APP_INFO__)
  81. }
  82. };
  83. };