如何在带有 typescript 的 React js 项目中使用 .env 文件?

问题描述 投票:0回答:5

我有一个 React js 项目,但是使用 TypeScript。我知道我们可以创建 .env 文件并定义一些配置,

.env 文件

REACT_APP_SOME_CONFIGURATION = "some value" 

并在代码中使用它,无需导入任何内容,如下所示

const configValue = process.env.REACT_APP_SOME_CONFIGURATION 

我在我的项目中尝试了这个设置,但没有成功。是因为它是打字稿吗?在这种情况下如何使用 .env 文件。

node.js reactjs typescript
5个回答
20
投票

在 TypeScript 中,您需要设置返回值,因此如果该字符串这样做的话

const configValue : string = process.env.REACT_APP_SOME_CONFIGURATION 

const configValue: string = (process.env.REACT_APP_SOME_CONFIGURATION as string);


9
投票

您可以将其添加到您的

react-app-env.d.ts
文件

declare namespace NodeJS {
    interface ProcessEnv {
       //types of envs
        NODE_ENV: 'development' | 'production' | 'test';
        PUBLIC_URL: string;

    }
}

3
投票

2021 年 3 月更新: 使用 React 17 和 typescript,您不需要设置返回“configValue”值,只需像以前一样使用 env 变量即可。 我的 .env 文件是这样的

REACT_APP_STRING=some_string_dont_have_quotation_mark

2
投票

对于像这样的失败场景,您可以将其更改为字符串或未定义

const configValue : string | undefined  = process.env.REACT_APP_SOME_CONFIGURATION


0
投票

如果您使用像 NextJs 这样的 React 框架,请小心,因为在 next 的情况下,环境变量可能会更改后缀。在 Node.js 中,公共范围的后缀是“NEXT_PUBLIC_”,因此考虑到实际的 TypeScript 版本,不需要指定代码的 var 类型

const configValue = process.env.NEXT_PUBLIC_SOME_CONFIGURATION

如果您希望更正确并强制 var 为字符串,我建议您

const configValue: string = (process.env.NEXT_PUBLIC_SOME_CONFIGURATION as string)
© www.soinside.com 2019 - 2024. All rights reserved.