1. .env
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/ :
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
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
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]
}
}
['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.