如何在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,但它没有帮助。
当前回答
我写了一个模块来简化它。它没有依赖关系,所以是相当轻量级的。它也适用于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)
其他回答
对于任何来这里寻找Create React App项目答案的人,你的变量名应该以REACT_APP_开头
更多信息请点击:https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
您可以为此使用类型断言
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中使用正确类型加载和清除环境变量的解决方案
使用节点进程的最佳和最简单的方法。你的typescript项目中的env是首先用tsc编译,然后用node提供你的env var运行编译后的javascript文件。ts是你想要的输出目录也是编译文件的名称,我使用dist作为输出目录和index.js为例):
cd my-typescriptproject
tsc
NODE_ENV=test node ./dist/index.js
执行typescript最新版本后:
NPM install——save @types/node
你可以使用过程。env直接。
console.log(process.env[“NODE_ENV”])
如果您设置了NODE_ENV,您将看到预期的结果。
补充了之前的回答,并在一段时间后解决了这个问题,甚至安装了@types/node,我找到了这个答案。简而言之,只需要运行一个重载窗口:
"...不过,如果typescript语言服务器仍然使用以前版本的tsconfig,则可能需要重新启动它。为了在VS Code中做到这一点,你可以按Ctrl+Shift+P并重新加载窗口或TypeScript:如果可用,重新启动TS服务器……”