DEV Community

Discussion on: 4 Reasons Not To Use Environment Variables

Collapse
 
brense profile image
Rense Bakker

In javascript/typescript I like to combine all ways to provide environment variables, using a sweet library called yargs :D

import dotenv from "dotenv"
import yargs from "yargs"
import fs from "fs"

dotenv.config()

const args = yargs
  .env() // parse process.env
  .middleware((argv) => {
    const configPath = "./config.json"
    if(fs.existsSync(configPath)){
      try {
        // parse options from config file
        return { ...JSON.parse(fs.readFileSync(configPath, 'utf-8')), ...argv }
      } catch(e){
        console.error('Error parsing config file')
      }
    }
    return argv
  }, true)
  .options({
    'port': { alias: 'p', type: 'number', default: 80 },
    'corsOrigin': { alias: 'o', type: 'string', default: "http://localhost:3000" },
    // etc... parses command line options
  })
  .help()
  .argv
Enter fullscreen mode Exit fullscreen mode

not sure if such a library exists for python though.