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

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

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

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


当前回答

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

其他回答

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

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

执行typescript最新版本后:

NPM install——save @types/node

你可以使用过程。env直接。

console.log(process.env[“NODE_ENV”])

如果您设置了NODE_ENV,您将看到预期的结果。

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

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

以下是我的envalid解决方案(在Node.js中验证和访问环境变量)

import { str, cleanEnv } from 'envalid'

const env = cleanEnv(process.env, {
  clientId: str(),
  clientSecret: str(),
})

// and now the env is validated and no longer undefined
const clientId = env.clientId

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

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