vite.config.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import { defineConfig, loadEnv } from "vite";
  2. import vue from "@vitejs/plugin-vue";
  3. import path from "node:path";
  4. import { createHtmlPlugin } from "vite-plugin-html";
  5. import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
  6. import { version } from "./package.json";
  7. import fs from 'fs'
  8. // https://vite.dev/config/
  9. export default ({ mode }: any) => {
  10. const env = loadEnv(mode, process.cwd());
  11. let proxy: any = {};
  12. if (env.VITE_MOCK_ENV) {
  13. const mockEnv = loadEnv(env.VITE_MOCK_ENV, process.cwd());
  14. const getProxy = (prev: string, api: string) => ({
  15. target: api,
  16. changeOrigin: true,
  17. rewrite: (path: any) => path.replace(prev, ""),
  18. });
  19. console.log(env, env.VITE_MOCK_ENV, mockEnv);
  20. if (env.VITE_MOCK_PROXY) {
  21. proxy[env.VITE_MOCK_PROXY] = getProxy(
  22. env.VITE_MOCK_PROXY,
  23. mockEnv.VITE_MOCK_PROXY
  24. );
  25. } else {
  26. for (const key in env) {
  27. if (env[key].includes("/") && env[key] !== mockEnv[key]) {
  28. proxy[env[key]] = getProxy(env[key], mockEnv[key]);
  29. }
  30. }
  31. }
  32. }
  33. console.log("===>", proxy);
  34. return defineConfig({
  35. build: {
  36. rollupOptions: {
  37. // 防止打包时处理指定目录
  38. external: [
  39. /^\/static\/models\/.*/, // 正则匹配 /static/models/ 下的所有文件
  40. ],
  41. },
  42. },
  43. base: "./",
  44. resolve: {
  45. alias: {
  46. "@/": `${path.resolve(__dirname, "src")}/`,
  47. },
  48. },
  49. css: {
  50. preprocessorOptions: {
  51. scss: {
  52. quietDeps: true,
  53. additionalData: `
  54. @forward 'element-plus/theme-chalk/src/common/var' with (
  55. $colors: (
  56. 'primary': (
  57. 'base': ${env.VITE_PRIMARY},
  58. ),
  59. ),
  60. );
  61. `,
  62. },
  63. },
  64. },
  65. server: {
  66. port: 9010,
  67. open: true,
  68. host: "0.0.0.0",
  69. proxy: proxy,
  70. },
  71. plugins: [
  72. {
  73. name: "remove-static-models",
  74. closeBundle() {
  75. const dir = path.resolve(__dirname, "dist/static/models");
  76. if (fs.existsSync(dir)) {
  77. fs.rmSync(dir, { recursive: true, force: true });
  78. console.log("Removed dist/static/models directory after build.");
  79. }
  80. },
  81. },
  82. createSvgIconsPlugin({
  83. iconDirs: [path.resolve(process.cwd(), "public/icons")],
  84. symbolId: "icon-[dir]-[name]",
  85. }),
  86. createHtmlPlugin({
  87. template: "index.html",
  88. entry: `/src${env.VITE_ENTRY}`,
  89. inject: {
  90. data: {
  91. title: env.VITE_TITLE,
  92. },
  93. },
  94. }),
  95. vue(),
  96. ],
  97. define: {
  98. __VERSION__: JSON.stringify(version),
  99. },
  100. });
  101. };