罗广辉
2026-06-12 eca1cdfd71119ef8cf855f52359986a24c4daf1f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import process from "node:process"
import { fileURLToPath, URL } from "node:url"
import { defineConfig, loadEnv } from "vite"
import { createViteProxy } from "./build/config/index"
import createVitePlugins from "./build/plugins/index"
import configEnv from "./src/config/env.js";
 
// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // mode: 区分生产环境还是开发环境
  console.log("command, mode -> ", command, mode)
 
  const { UNI_PLATFORM,UNI_CUSTOM_DEFINE } = process.env
  const ENV_NAME = UNI_CUSTOM_DEFINE && JSON.parse(UNI_CUSTOM_DEFINE)?.ENV_NAME
  const __APP_ENV__ = {
    UNI_PLATFORM: UNI_PLATFORM,
    ENV_NAME: ENV_NAME || 'development'
  }
  console.log("平台 -> ", __APP_ENV__.UNI_PLATFORM) // 得到 mp-weixin, h5, app 等
  console.log("环境 -> ", __APP_ENV__.ENV_NAME) // 得到 development,test 等
 
  const env = loadEnv(mode, fileURLToPath(new URL("./env", import.meta.url)))
  // console.log("环境变量 env -> ", env)
  const isBuild = process.env.NODE_ENV === "production"
  return {
    define: {
      __APP_ENV__,
    },
    // 自定义env目录
    envDir: "./env",
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: {
        // 设置别名
        "@": fileURLToPath(new URL("./src", import.meta.url))
      }
    },
    // vite 相关配置
    server: {
      port: Number.parseInt(env.VITE_APP_PORT, 10),
      hmr: true,
      host: true,
      open: true,
      proxy: createViteProxy(env,__APP_ENV__.ENV_NAME)
    },
    // 设置scss的api类型为modern-compiler
    css: {
      preprocessorOptions: {
        scss: {
          api: "modern-compiler",
          // 消除一些不必要的警告
          silenceDeprecations: ["legacy-js-api"]
        }
      }
    },
    plugins: createVitePlugins(isBuild),
    esbuild: {
      drop: JSON.parse(env.VITE_DROP_CONSOLE) ? ["console", "debugger"] : []
    }
  }
})