'how to use .env file in a react js with typescript project?
I have a react js project , but with typescript. I understand we can create .env file and have some configuration defined as such,
.env file
REACT_APP_SOME_CONFIGURATION = "some value"
and use it in the code , without importing anything , like below
const configValue = process.env.REACT_APP_SOME_CONFIGURATION
I tried this set up in my project , and it didn't work. is it because it is typescript? how to use .env file in such scenario.
Solution 1:[1]
In TypeScript, you need to set the return value so if this string did so
const configValue : string = process.env.REACT_APP_SOME_CONFIGURATION
OR
const configValue: string = (process.env.REACT_APP_SOME_CONFIGURATION as string);
Solution 2:[2]
Update on March 2021: With React 17 and typescript, you don't need to set the return the 'configValue' value, just use the env variable like you did before. My .env file like this
REACT_APP_STRING=some_string_dont_have_quotation_mark
Solution 3:[3]
You could change this to a string or Undefined for a failing scenario like so
const configValue : string | undefined = process.env.REACT_APP_SOME_CONFIGURATION
Solution 4:[4]
You can add this to your react-app-env.d.ts
file
declare namespace NodeJS {
interface ProcessEnv {
//types of envs
NODE_ENV: 'development' | 'production' | 'test';
PUBLIC_URL: string;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yoel |
Solution 2 | Dang Kien |
Solution 3 | Oladele Seyi |
Solution 4 | Heet Vakharia |