React

[React] React + Vite 에서 dotenv 사용하기

hazel__ 2022. 4. 17. 20:04

react와 vite를 사용하여 프런트엔드 코드를 구현했다.

 

문제

node.js 에서 사용하듯이 아래와 같은 코드로 작성했다.

require("dotenv").config();

console.log(process.env.KEY);

위의 코드의 출력 결과는  undefined  !

 

또는 아래의 오류가 발생한다.

ReferenceError: process is not defined

우선, VITE에서는 process를 사용하지 않는다. 그럼 자동으로 파일을 읽어오는 건가? 했지만,

dotenv 파일을 자동으로 읽어오지 않는다.

 

 


 

해결 방법

우선 env 파일의 경로를 설정한다.

 기본적으로 root로 설정되어 있다.

//vite.config.ts
export default defineConfig({
	plugins: [react()],
	server: {
		port: 4242,
	},
	envDir: "src",
})

 

https://vitejs.dev/config/#envdir

 

Configuring Vite | Vite

Configuring Vite Config File Config File Resolving When running vite from the command line, Vite will automatically try to resolve a config file named vite.config.js inside project root. The most basic config file looks like this: Note Vite supports using

vitejs.dev

 

 

env 파일의 경로에 env.d.ts 파일을 작성하여 타입을 선언한다.

이는 typescript를 사용하는 경우에만 작성한다!!

 

//env.d.ts
interface ImportMetaEnv {
	readonly VITE_KEY: string,
	readonly VITE_QUOTE: string,
}

interface ImportMeta {
	readonly env: ImportMetaEnv
}

 

 

그러고 나서, 같은 위치에 dotenv 파일을 작성하면 된다.

//dotenv
VITE_KEY=STRING
VITE_QUOTE=STRING

이때, vite의 키 값은 항상 VITE_ 를 붙여 사용해야 한다.

VITE_  prefix 가 없는 경우, 무시된다.

 

 

prefix는 수정 가능하며, 아래의 공식 문서를 참고하여 작성하면 가능하다!

https://vitejs.dev/config/#envprefix

 

Configuring Vite | Vite

Configuring Vite Config File Config File Resolving When running vite from the command line, Vite will automatically try to resolve a config file named vite.config.js inside project root. The most basic config file looks like this: Note Vite supports using

vitejs.dev

 

 

 

마지막으로, dotenv에 작성한 값이 잘 나오는지 확인해보자!!

console.log(import.meta.env.VITE_KEY);
console.log(import.meta.env.VITE_QUOTE);

위와 같이 import.meta.env로 접근하여 사용할 수 있다.

따로 import 할 모듈은 없다!

 

 

 

구글링 보다 공식 문서를 먼저 확인하자!!!!!