[英]how to use .env file in a react js with typescript project?
我有一個 React js 項目,但是有 typescript。我知道我們可以創建 .env 文件並定義一些配置,
.env 文件
REACT_APP_SOME_CONFIGURATION = "some value"
並在代碼中使用它,無需導入任何內容,如下所示
const configValue = process.env.REACT_APP_SOME_CONFIGURATION
我在我的項目中嘗試了這個設置,但它沒有用。 是因為它是typescript嗎? 在這種情況下如何使用 .env 文件。
您可以將其添加到您的react-app-env.d.ts
文件中
declare namespace NodeJS {
interface ProcessEnv {
//types of envs
NODE_ENV: 'development' | 'production' | 'test';
PUBLIC_URL: string;
}
}
在 TypeScript 中,你需要設置返回值,如果這個字符串這樣做了
const configValue : string = process.env.REACT_APP_SOME_CONFIGURATION
或者
const configValue: string = (process.env.REACT_APP_SOME_CONFIGURATION as string);
2021 年 3 月更新:使用 React 17 和打字稿,您無需設置返回值 'configValue' 值,只需像以前一樣使用 env 變量即可。 我的 .env 文件是這樣的
REACT_APP_STRING=some_string_dont_have_quotation_mark
對於像這樣的失敗場景,您可以將其更改為字符串或未定義
const configValue : string | undefined = process.env.REACT_APP_SOME_CONFIGURATION
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.