如何在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,但它没有帮助。
当前回答
对于任何来这里寻找Create React App项目答案的人,你的变量名应该以REACT_APP_开头
更多信息请点击:https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
其他回答
执行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!;
我知道这将帮助一些人搜索这个,不能找到简单的答案,为什么你的过程。Env变量让你的编译器抱怨:
安装@types /节点:
npm i @types/node
然后当你将env作为字符串包含时,这样做:
process.env.YOUR_ENV ?? ''
双问号允许您检查null/undefined。
创建一个类似global.d.ts的文件
declare global {
namespace NodeJS {
interface ProcessEnv {
SECRET: string;
}
}
}
export {};
教程由克里斯蒂安Höller
您可以为此使用类型断言
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中使用正确类型加载和清除环境变量的解决方案