Using process.env in TypeScript

How to read node environment variables in TypeScript?

If I use process.env.NODE_ENV, I have this error:

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

I installed @types/node, but that did not help.

+19
source share
9 answers

There is no guarantee that (if any) environment variables will be available in the Node process - a variable NODE_ENVis just an agreement that was popularized by Express, and not something built into Node itself. Thus, it makes no sense to include it in type definitions. Instead, they are defined process.envas follows :

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

, process.env , ( undefined, ). , :

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

, jcalz , TypeScript 2.2 , , , - .

+10

@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;
    }
  }
}

IntelliSense, .

: . , , ( ). , /.

TypeScript , import. . import * as ts from 'typescript' .

+11

process.env.NODE_ENV :

declare var process : {
  env: {
    NODE_ENV: string
  }
}
+8

:

npm install --save @types/node

process.env .

console.log(process.env["NODE_ENV"])

, NODE_ENV.

+5

for this

, , TypeScript. , , .

- " , , " .' , . . TypeScript , , - , .

const nodeEnv: string = (process.env.NODE_ENV as string);
console.log(nodeEnv);

, env-var, -

" node.js "

+5

1. .env

# Contents of .env file
AUTHENTICATION_API_URL="http://localhost:4000/login"
GRAPHQL_API_URL="http://localhost:4000/graphql"

2. .env process.env dotenv

dotenv process.env dotenv . config.ts src/ :

// Contents of src/config.ts

import {config as configDotenv} from 'dotenv'
import {resolve} from 'path'

switch(process.env.NODE_ENV) {
  case "development":
    console.log("Environment is 'development'")
    configDotenv({
      path: resolve(__dirname, "../.env.development")
    })
    break
  case "test":
    configDotenv({
      path: resolve(__dirname, "../.env.test")
    })
    break
  // Add 'staging' and 'production' cases here as well!
  default:
    throw new Error(''NODE_ENV' ${process.env.NODE_ENV} is not handled!')
}

. , , src/index.ts import './config' ( ).

3. ENV IProcessEnv

, , IProcessEnv , IProcessEnv , ENV .env.*. src/config.ts

// More content in config.ts
const throwIfNot = <T, K extends keyof T>(obj: Partial<T>, prop: K, msg?: string): T[K] => {
  if(obj[prop] === undefined || obj[prop] === null){
    throw new Error(msg || 'Environment is missing variable ${prop}')
  }else {
    return obj[prop] as T[K]
  }
}
// Validate that we have our expected ENV variables defined!
['AUTHENTICATION_API_URL', 'GRAPHQL_API_URL'].forEach(v => {
  throwIfNot(process.env, v)
}

export interface IProcessEnv {
  AUTHENTICATION_API_URL: string
  GRAPHQL_API_URL: string
}

declare global {
  namespace NodeJS {
    interface ProcessEnv extends IProcessEnv { }
  }
}

IntelliSense/tslint, .

, ReactJS ( NodeJS). (2), create-react-app.

+1

, process.env .

- ( ) env-var.

/**
 * Returns value stored in environment variable with the given 'name'.
 * Throws Error if no such variable or if variable undefined; thus ensuring type-safety.
 * @param name - name of variable to fetch from this process environment.
 */
export function env(name: string): string {
  const value = process.env[name];

  if (!value) {
    throw new Error('Missing: process.env['${name}'].');
  }

  return value;
}

:

let currentEnvironment: string;
currentEnvironment = env('NODE_ENV');
+1

.env TypeScrype, ( bash):

1- .env .

2- npm- package.json.

3- . /dev.sh . set -a; source.env; set +a; npm run dev

. /dev.sh .

In this way, environment variables are set. If you set PORT = 3000 in a file, you can access it using:process.env.PORT

0
source

Source: https://habr.com/ru/post/1681799/


All Articles