如何在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,但它没有帮助。
当前回答
还可以使用类型保护函数。像这样,返回类型是
parameterName is string
如。
function isEnvVarSpecified(envVar: string | undefined): envVar is string {
if(envVar === undefined || envVar === null) {
return false;
}
if(typeof envVar !== 'string'){
return false;
}
return true;
}
然后你可以调用它作为类型保护:
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
}
其他回答
补充了之前的回答,并在一段时间后解决了这个问题,甚至安装了@types/node,我找到了这个答案。简而言之,只需要运行一个重载窗口:
"...不过,如果typescript语言服务器仍然使用以前版本的tsconfig,则可能需要重新启动它。为了在VS Code中做到这一点,你可以按Ctrl+Shift+P并重新加载窗口或TypeScript:如果可用,重新启动TS服务器……”
只需对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));
创建一个类似global.d.ts的文件
declare global {
namespace NodeJS {
interface ProcessEnv {
SECRET: string;
}
}
}
export {};
教程由克里斯蒂安Höller
重要提示:如果你有一个web应用程序,你正在使用webpack。定义流程。Env在你的窗户上,那么这些就是你要找的类型:
declare namespace process {
let env: {
// this is optional, if you want to allow also
// other values than the ones listed below, they will have type
// string | undefined, which is the default
[key: string]: string
commit_hash: string
build_time: string
stage: string
version: string
// ... etc.
}
}
在使用process.env之前添加即可。NODE_ENV跟随行:
declare var process : {
env: {
NODE_ENV: string
}
}