node.js 在 TypeScript 中使用 process.env
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45194598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using process.env in TypeScript
提问by Christophe Le Besnerais
How do I read node environment variables in TypeScript?
如何在 TypeScript 中读取节点环境变量?
If i use process.env.NODE_ENVI have this error :
如果我使用process.env.NODE_ENV我有这个错误:
Property 'NODE_ENV' does not exist on type 'ProcessEnv'
I have installed @types/nodebut it didn't help.
我已经安装,@types/node但没有帮助。
采纳答案by Joe Clay
There's no guarantee of what (if any) environment variables are going to be available in a Node process - the NODE_ENVvariable is just a convention that was popularised by Express, rather than something built in to Node itself. As such, it wouldn't really make sense for it to be included in the type definitions. Instead, they define process.envlike this:
无法保证在 Node 进程中可以使用哪些(如果有)环境变量 - 该NODE_ENV变量只是 Express 推广的约定,而不是 Node 本身内置的东西。因此,将它包含在类型定义中实际上没有意义。相反,他们定义process.env如下:
export interface ProcessEnv {
[key: string]: string | undefined
}
Which means that process.envcan be indexed with a string in order to get a string back (or undefined, if the variable isn't set). To fix your error, you'll have to use the index syntax:
这意味着process.env可以用字符串索引以取回字符串(或者undefined,如果未设置变量)。要修复您的错误,您必须使用索引语法:
let env = process.env["NODE_ENV"];
Alternatively, as jcalz pointed out in the comments, if you're using TypeScript 2.2 or newer, you can access indexable types like the one defined above using the dot syntax - in which case, your code should just work as is.
或者,正如 jcalz 在评论中指出的那样,如果您使用的是 TypeScript 2.2 或更新版本,您可以使用点语法访问上面定义的可索引类型 - 在这种情况下,您的代码应该按原样工作。
回答by Karol Majewski
Once you have installed @types/nodein your project, you can tell TypeScript exactly what variables are present in your process.env:
@types/node在项目中安装后,您可以准确地告诉 TypeScript 中存在哪些变量process.env:
environment.d.ts
environment.d.ts
declare global {
namespace NodeJS {
interface ProcessEnv {
GITHUB_AUTH_TOKEN: string;
NODE_ENV: 'development' | 'production';
PORT?: string;
PWD: string;
}
}
}
// If this file has no import/export statements (i.e. is a script)
// convert it into a module by adding an empty export statement.
export {}
Usage:
用法:
process.env.GITHUB_AUTH_TOKEN; // $ExpectType string
This method will give you IntelliSense, and it also takes advantage of string literal types.
此方法将为您提供 IntelliSense,并且它还利用了字符串文字类型。
Note: the snippet above is module augmentation. Files containing module augmentation must be modules(as opposed to scripts). The difference between modules and scripts is that modules have at least one import/export statement.
In order to make TypeScript treat your file as a module, just add one import statement to it. It can be anything. Even
export {}will do.
注意:上面的代码片段是模块扩充。包含模块扩充的文件必须是模块(而不是脚本)。模块和脚本的区别在于模块至少有一个导入/导出语句。
为了让 TypeScript 将您的文件视为一个模块,只需向其中添加一个 import 语句。它可以是任何东西。甚至
export {}会做。
回答by haiflive
just add before use process.env.NODE_ENVfollow lines:
只需在使用前添加process.env.NODE_ENV以下行:
declare var process : {
env: {
NODE_ENV: string
}
}
回答by Ville
You can use a Type Assertionfor this
您可以为此使用类型断言
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.
有时,您最终会遇到比 TypeScript 更了解值的情况。通常,当您知道某个实体的类型可能比其当前类型更具体时,就会发生这种情况。
类型断言是一种告诉编译器“相信我,我知道我在做什么”的方式。类型断言类似于其他语言中的类型转换,但不执行特殊的数据检查或重组。它没有运行时影响,纯粹由编译器使用。TypeScript 假定您,程序员,已经执行了您需要的任何特殊检查。
Example
例子
const nodeEnv: string = (process.env.NODE_ENV as string);
console.log(nodeEnv);
Alternatively you might find a library such as env-varmore suitable for this specific purpose --
或者,您可能会发现诸如env-var 之类的库更适合此特定目的——
"solution for loading and sanitizing environment variables in node.js with correct typings"
“使用正确的类型加载和清理 node.js 中的环境变量的解决方案”
回答by pwxcoo
After executing with typescript latest version:
使用打字稿最新版本执行后:
npm install --save @types/node
npm install --save @types/node
you can use process.envdirectly.
可以process.env直接使用。
console.log(process.env["NODE_ENV"])
console.log(process.env["NODE_ENV"])
you will see the expected result if you have set NODE_ENV.
如果您设置了,您将看到预期的结果NODE_ENV。
回答by The Aelfinn
1. Create a .envfile
1.创建.env文件
# Contents of .env file
AUTHENTICATION_API_URL="http://localhost:4000/login"
GRAPHQL_API_URL="http://localhost:4000/graphql"
2. Load your .envfile into process.envwith dotenv
2.将.env文件转换成process.env与dotenv
We can leverage dotenvto set environment-specific process.envvariables. Create a file called config.tsin your src/directory and populate as follows:
我们可以利用dotenv来设置特定于环境的process.env变量。config.ts在您的src/目录中创建一个名为的文件并按如下方式填充:
// Contents of src/config.ts
import {config as configDotenv} from 'dotenv'
import {resolve} from 'path'
switch(process.env.NODE_ENV) {
case "development":
console.log("Environment is 'development'")
configDotenv({
path: resolve(__dirname, "../.env.development")
})
break
case "test":
configDotenv({
path: resolve(__dirname, "../.env.test")
})
break
// Add 'staging' and 'production' cases here as well!
default:
throw new Error(`'NODE_ENV' ${process.env.NODE_ENV} is not handled!`)
}
Note:This file needs to get imported in your top-most file, likely your src/index.ts viaimport './config'(placed before all other imports)
注意:此文件需要通过import './config'(放置在所有其他导入之前)导入您的最顶层文件,可能是您的 src/index.ts
3. Check ENV variables and define IProcessEnv
3. 检查 ENV 变量并定义 IProcessEnv
After combining a few methods above, we can add some runtime checks for sanity to guarantee that our declared IProcessEnvinterface reflects what ENV variables are set in our .env.*files. The contents below can also live in src/config.ts
结合上述几种方法后,我们可以添加一些运行时检查以确保我们声明的IProcessEnv接口反映在我们的.env.*文件中设置的 ENV 变量。下面的内容也可以在src/config.ts
// More content in config.ts
const throwIfNot = <T, K extends keyof T>(obj: Partial<T>, prop: K, msg?: string): T[K] => {
if(obj[prop] === undefined || obj[prop] === null){
throw new Error(msg || `Environment is missing variable ${prop}`)
}else {
return obj[prop] as T[K]
}
}
// Validate that we have our expected ENV variables defined!
['AUTHENTICATION_API_URL', 'GRAPHQL_API_URL'].forEach(v => {
throwIfNot(process.env, v)
})
export interface IProcessEnv {
AUTHENTICATION_API_URL: string
GRAPHQL_API_URL: string
}
declare global {
namespace NodeJS {
interface ProcessEnv extends IProcessEnv { }
}
}
This will give us proper IntelliSense/tslint type checking, as well as some sanity when deploying to various environments.
这将为我们提供适当的 IntelliSense/tslint 类型检查,以及在部署到各种环境时的一些理智。
Notethat this also works for a ReactJS app (as opposed to a NodeJS server app). You can omit Step (2)because this is handled by create-react-app.
请注意,这也适用于 ReactJS 应用程序(与NodeJS服务器应用程序相反)。您可以省略步骤 (2),因为这是由 处理的create-react-app。
回答by Peter W
Here is a short function which is guaranteed to pull the process.env value as a string -- or to throw an error otherwise.
这是一个简短的函数,它保证将 process.env 值作为字符串提取——否则会抛出错误。
For something more powerful (but also bigger), others here have suggested env-var.
对于更强大(但也更大)的东西,这里的其他人建议使用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;
}
You should then be able to write code like:
然后,您应该能够编写如下代码:
let currentEnvironment: string;
currentEnvironment = env('NODE_ENV');
回答by gkri
For anyone coming here looking for an answer for React projects specifically, your variable names should start with REACT_APP_
对于来这里寻找 React 项目答案的人来说,你的变量名应该以 REACT_APP_
Read more here: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
在此处阅读更多信息:https: //facebook.github.io/create-react-app/docs/adding-custom-environment-variables
回答by Ross Coundon
You could also use a type guard function. Something like this that has a return type of
您还可以使用类型保护功能。像这样的东西有一个返回类型
parameterName is string
e.g.
例如
function isEnvVarSpecified(envVar: string | undefined): envVar is string {
if(envVar === undefined || envVar === null) {
return false;
}
if(typeof envVar !== 'string'){
return false;
}
return true;
}
You can then call this as a type guard:
然后,您可以将其称为类型保护:
function myFunc() {
if(!isEnvVarSpecified(process.env.SOME_ENV_VAR')){
throw new Error('process.env.SOME_ENV_VAR not found')
}
// From this point on the ts compiler won't complain about
// process.env.SOME_ENV_VAR being potentially undefined
}
回答by Erycoking
what worked for me is that everywhere I want to use process.envI first import dotenvand call config()on it. Also, remember to append !at the end and ensure the attribute is defined in your .envfile
对我有用的是,在我想使用的任何地方,process.env我首先导入dotenv并调用config()它。另外,请记住在末尾追加!并确保在您的.env文件中定义了该属性
import dotenv from 'dotenv';
dotenv.config();
export const YOUR_ATTRIBUTE = process.env.YOUR_ATTRIBUTE!;

