可以使用 vite 提供的loadEnv
方法。
1、获取当前环境变量对象
export default ({ mode }) => {
//参数mode为开放模式或生产模式
//console.log(mode); // development or product
const currentEnv = loadEnv(mode, process.cwd()); // 获取.env文件里定义的环境变量
};
2、获取当前环境变量对象中的某个值
const loadEnvByMode = (mode, env) => {
return loadEnv(mode, process.cwd())[env];
};
export default defineConfig(({ mode }) => {
// 获取环境变量
const currentEnv = loadEnv(mode, process.cwd());
console.log('⭐mode==>', mode);
console.log('当前环境==>', process.env.NODE_ENV);
console.log('currentEnv==>', currentEnv);
return {
server: {
open: true,
host: '0.0.0.0',
proxy: {
'/api': {
target: loadEnvByMode(mode, 'VITE_PROXY_URL'),
// target: 'https://cloud.whtyinfo.com/dev-bluelinkup/services/ops',
changeOrigin: true,
ws: true,
rewrite: (path) => path.replace(/^\/api/, ''),
headers: {
Referer: 'https://cloud.whtyinfo.com',
},
},
},
},
};
});