如何在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,但它没有帮助。
当前回答
使用节点进程的最佳和最简单的方法。你的typescript项目中的env是首先用tsc编译,然后用node提供你的env var运行编译后的javascript文件。ts是你想要的输出目录也是编译文件的名称,我使用dist作为输出目录和index.js为例):
cd my-typescriptproject
tsc
NODE_ENV=test node ./dist/index.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');
通过运行npm i @types/node安装@types/node 在tsconfig中添加"types": ["node"]。json文件在compilerSection部分。
我写了一个模块来简化它。它没有依赖关系,所以是相当轻量级的。它也适用于dotenv,您可以传递一个自定义进程。Env到Env .from函数,如果需要的话。
在一些回答中已经提到了它,但这里有一个例子:
使用yarn/npm安装:
npm install env-var --save
然后读取变量:
import * as env from 'env-var'
// Read NODE_ENV and verify that:
// 1) it is set using the required() function
// 2) it is either 'dev' or 'prod'
// 3) throw a runtime exception if conditions #1 or #2 fail
const environment = env.get('NODE_ENV').required().asEnum(['dev', 'prod'])
// Intellisense will suggest 'dev' or 'prod'
if (environment === 'dev') {
console.log('yep, this is dev')
} else {
console.log('looks like this is prod')
}
或另一个:
import { get } from 'env-var'
// Read the GitHub token. It could be undefined
const githubToken = get('GITHUB_TOKEN').asString()
// Read MAX_CONCURRENCY, or default to 5. Throw an error if it's
// not set to a positive integer value
const concurrencyLimit = get('MAX_CONCURRENCY').default(5).asIntPositive()
function callGitApi (token: string, concurrency: number) { /* implementation */ }
// TS Error: Argument of type 'string | undefined' is not assignable to
// parameter of type 'string'.
callGitApi(githubToken, concurrencyLimit)
我知道这将帮助一些人搜索这个,不能找到简单的答案,为什么你的过程。Env变量让你的编译器抱怨:
安装@types /节点:
npm i @types/node
然后当你将env作为字符串包含时,这样做:
process.env.YOUR_ENV ?? ''
双问号允许您检查null/undefined。
一旦你在你的项目中安装了@types/node,你就可以告诉TypeScript process.env中到底有哪些变量:
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 {}
用法:
process.env.GITHUB_AUTH_TOKEN; // $ExpectType string
此方法将为您提供智能感知,并且它还利用了字符串文字类型。
注意:上面的代码片段是模块扩展。包含模块扩展的文件必须是模块(而不是脚本)。模块和脚本的区别在于模块至少有一个导入/导出语句。 为了让TypeScript把你的文件当成一个模块,只需要给它添加一个import语句。它可以是任何东西。甚至export{}也可以。