1。创建一个.env 文件
# Contents of .env file
AUTHENTICATION_API_URL="http://localhost:4000/login"
GRAPHQL_API_URL="http://localhost:4000/graphql"
2。使用dotenv 将您的.env 文件加载到process.env
我们可以利用dotenv 设置特定于环境的process.env 变量。在您的src/ 目录中创建一个名为config.ts 的文件并按如下方式填充:
// 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 接口反映了我们.env.* 文件中设置的ENV 变量。下面的内容也可以住在src/config.ts
// More content in config.ts
const throwIfNot = function<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 处理的。