如何在TypeScript中读取节点环境变量?

如果我使用process.env。NODE_ENV我有这个错误:

Property 'NODE_ENV' does not exist on type 'ProcessEnv'

我已经安装了@types/node,但它没有帮助。


当前回答

并不能保证在Node进程中可用的环境变量是什么(如果有的话)——NODE_ENV变量只是一个由Express推广的约定,而不是Node本身内置的东西。因此,将它包含在类型定义中实际上没有意义。相反,他们定义过程。这样的环境:

export interface ProcessEnv {
    [key: string]: string | undefined
}

这意味着这个过程。Env可以用字符串进行索引,以便返回字符串(如果没有设置变量,则为undefined)。要修复你的错误,你必须使用索引语法:

let env = process.env["NODE_ENV"];

或者,正如jcalz在评论中指出的那样,如果你使用的是TypeScript 2.2或更新版本,你可以使用点语法访问上面定义的可索引类型——在这种情况下,你的代码应该可以正常工作。

其他回答

对于任何来这里寻找Create React App项目答案的人,你的变量名应该以REACT_APP_开头

更多信息请点击:https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

在使用process.env之前添加即可。NODE_ENV跟随行:

declare var process : {
  env: {
    NODE_ENV: string
  }
}

您可以为此使用类型断言

Sometimes you’ll end up in a situation where you’ll know more about a value than TypeScript does. Usually this will happen when you know the type of some entity could be more specific than its current type. Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

例子

const nodeEnv: string = (process.env.NODE_ENV as string);
console.log(nodeEnv);

或者,您可能会发现像env-var这样的库更适合这个特定的目的——

在node.js中使用正确类型加载和清除环境变量的解决方案

对我有用的是,无论我想在哪里使用过程。我首先导入dotenv并在它上面调用config()。另外,记得附加!最后,确保在.env文件中定义了该属性

从'dotenv'导入dotenv; dotenv.config (); export const YOUR_ATTRIBUTE = process.env.YOUR_ATTRIBUTE!;

通过运行npm i @types/node安装@types/node 在tsconfig中添加"types": ["node"]。json文件在compilerSection部分。