如何在TypeScript中读取节点环境变量?
如果我使用process.env。NODE_ENV我有这个错误:
Property 'NODE_ENV' does not exist on type 'ProcessEnv'
我已经安装了@types/node,但它没有帮助。
如何在TypeScript中读取节点环境变量?
如果我使用process.env。NODE_ENV我有这个错误:
Property 'NODE_ENV' does not exist on type 'ProcessEnv'
我已经安装了@types/node,但它没有帮助。
当前回答
通过运行npm i @types/node安装@types/node 在tsconfig中添加"types": ["node"]。json文件在compilerSection部分。
其他回答
下面是一个简短的函数,它保证会拉动进程。将Env值作为字符串—或以其他方式抛出错误。
对于更强大(但也更大)的东西,这里的其他人建议使用env-var。
/**
* Returns value stored in environment variable with the given `name`.
* Throws Error if no such variable or if variable undefined; thus ensuring type-safety.
* @param name - name of variable to fetch from this process's environment.
*/
export function env(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Missing: process.env['${name}'].`);
}
return value;
}
然后你应该能够编写如下代码:
let currentEnvironment: string;
currentEnvironment = env('NODE_ENV');
您可以为此使用类型断言
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中使用正确类型加载和清除环境变量的解决方案
对于任何来这里寻找Create React App项目答案的人,你的变量名应该以REACT_APP_开头
更多信息请点击:https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
补充了之前的回答,并在一段时间后解决了这个问题,甚至安装了@types/node,我找到了这个答案。简而言之,只需要运行一个重载窗口:
"...不过,如果typescript语言服务器仍然使用以前版本的tsconfig,则可能需要重新启动它。为了在VS Code中做到这一点,你可以按Ctrl+Shift+P并重新加载窗口或TypeScript:如果可用,重新启动TS服务器……”
并不能保证在Node进程中可用的环境变量是什么(如果有的话)——NODE_ENV变量只是一个由Express推广的约定,而不是Node本身内置的东西。因此,将它包含在类型定义中实际上没有意义。相反,他们定义过程。这样的环境:
export interface ProcessEnv {
[key: string]: string | undefined
}
这意味着这个过程。Env可以用字符串进行索引,以便返回字符串(如果没有设置变量,则为undefined)。要修复你的错误,你必须使用索引语法:
let env = process.env["NODE_ENV"];
或者,正如jcalz在评论中指出的那样,如果你使用的是TypeScript 2.2或更新版本,你可以使用点语法访问上面定义的可索引类型——在这种情况下,你的代码应该可以正常工作。