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

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

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

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


当前回答

补充了之前的回答,并在一段时间后解决了这个问题,甚至安装了@types/node,我找到了这个答案。简而言之,只需要运行一个重载窗口:

"...不过,如果typescript语言服务器仍然使用以前版本的tsconfig,则可能需要重新启动它。为了在VS Code中做到这一点,你可以按Ctrl+Shift+P并重新加载窗口或TypeScript:如果可用,重新启动TS服务器……”

其他回答

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

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

只需对process.env.YOUR_VAR进行类型转换

例子:

mongoose
  .connect(String(process.env.MONGO_URL), {
    useNewUrlParser: true,
    useFindAndModify: false
  })
  .then(() => console.log('DB connected'))
  .catch((err: any) => console.error(err));

您可以为此使用类型断言

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中使用正确类型加载和清除环境变量的解决方案

下面是一个简短的函数,它保证会拉动进程。将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');

创建一个类似global.d.ts的文件


declare global {
  namespace NodeJS {
    interface ProcessEnv {
      SECRET: string;
    }
  }
}
export {};

教程由克里斯蒂安Höller