카테고리 없음

[Vite] Using Environment Variables in Config

Withlaw 2024. 1. 25. 22:45

1. 개요

보통 환경 변수는 process.env를 통해 접근할 수 있다. 하지만 vite에서는 config 파일을 먼저 평가한 후에 불러올 파일을 결정하기 때문에 .env에 바로 접근할 수 없다.

 

즉 command('serve' or 'build')나 mode('production' or 'development') 등의 설정 값에 의해 실행 환경이 동적으로 변경될 수 있고, 이에 따라 vite가 불러오는 파일이 달라질 수 있다.

 

환경 변수 역시 현재 앱이 실행되는 모드나 .env 폴더 위치에 따라 달라 질 수 있다.

 

 

2. 프록시 서버 타겟을 환경 변수를 사용하여 설정하는 방법 

import { defineConfig, loadEnv } from 'vite';

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), 'VITE');

  return {
    // vite config ...
    server: {
      proxy: {
        '/api': {
          target: env.VITE_BASE_URL,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, ''),
        },
      },
    },
  };
});

 

참고: https://vitejs.dev/config/#using-environment-variables-in-config