【问题标题】:how to use .env file in a react js with typescript project?如何在带有 typescript 项目的 react js 中使用 .env 文件?
【发布时间】:2021-02-03 17:55:37
【问题描述】:

我有一个 react js 项目,但带有打字稿。我知道我们可以创建 .env 文件并定义一些配置,

.env 文件

REACT_APP_SOME_CONFIGURATION = "some value" 

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

const configValue = process.env.REACT_APP_SOME_CONFIGURATION 

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

【问题讨论】:

标签: node.js reactjs typescript


【解决方案1】:

在 TypeScript 中,你需要设置返回值,所以如果这个字符串这样做了

const configValue : string = process.env.REACT_APP_SOME_CONFIGURATION 

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

【讨论】:

  • 你是救生员
【解决方案2】:

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

REACT_APP_STRING=some_string_dont_have_quotation_mark

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 2018-03-15
      • 2019-12-13
      • 2016-12-24
      • 2018-12-31
      相关资源
      最近更新 更多