如何在TypeScript中读取节点环境变量?

如果我使用process.env。NODE_ENV我有这个错误:

Property 'NODE_ENV' does not exist on type 'ProcessEnv'

我已经安装了@types/node,但它没有帮助。


当前回答

重要提示:如果你有一个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.
    }
}

其他回答

并不能保证在Node进程中可用的环境变量是什么(如果有的话)——NODE_ENV变量只是一个由Express推广的约定,而不是Node本身内置的东西。因此,将它包含在类型定义中实际上没有意义。相反,他们定义过程。这样的环境:

export interface ProcessEnv {
    [key: string]: string | undefined
}

这意味着这个过程。Env可以用字符串进行索引,以便返回字符串(如果没有设置变量,则为undefined)。要修复你的错误,你必须使用索引语法:

let env = process.env["NODE_ENV"];

或者,正如jcalz在评论中指出的那样,如果你使用的是TypeScript 2.2或更新版本,你可以使用点语法访问上面定义的可索引类型——在这种情况下,你的代码应该可以正常工作。

通过运行npm i @types/node安装@types/node 在tsconfig中添加"types": ["node"]。json文件在compilerSection部分。

创建一个类似global.d.ts的文件


declare global {
  namespace NodeJS {
    interface ProcessEnv {
      SECRET: string;
    }
  }
}
export {};

教程由克里斯蒂安Höller

使用节点进程的最佳和最简单的方法。你的typescript项目中的env是首先用tsc编译,然后用node提供你的env var运行编译后的javascript文件。ts是你想要的输出目录也是编译文件的名称,我使用dist作为输出目录和index.js为例):

cd my-typescriptproject
tsc
NODE_ENV=test node ./dist/index.js

对于任何来这里寻找Create React App项目答案的人,你的变量名应该以REACT_APP_开头

更多信息请点击:https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables