如何在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,但它没有帮助。
当前回答
补充了之前的回答,并在一段时间后解决了这个问题,甚至安装了@types/node,我找到了这个答案。简而言之,只需要运行一个重载窗口:
"...不过,如果typescript语言服务器仍然使用以前版本的tsconfig,则可能需要重新启动它。为了在VS Code中做到这一点,你可以按Ctrl+Shift+P并重新加载窗口或TypeScript:如果可用,重新启动TS服务器……”
其他回答
一旦你在你的项目中安装了@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{}也可以。
执行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!;
补充了之前的回答,并在一段时间后解决了这个问题,甚至安装了@types/node,我找到了这个答案。简而言之,只需要运行一个重载窗口:
"...不过,如果typescript语言服务器仍然使用以前版本的tsconfig,则可能需要重新启动它。为了在VS Code中做到这一点,你可以按Ctrl+Shift+P并重新加载窗口或TypeScript:如果可用,重新启动TS服务器……”
您可以为此使用类型断言
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中使用正确类型加载和清除环境变量的解决方案