Created
January 17, 2019 13:41
-
-
Save alexalexandrescu/a61002d5da86094336024d0e505f83cc to your computer and use it in GitHub Desktop.
SImple nodejs script that uses .env to generate environment.ts for Angular projects made to work on a lot of environments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env node | |
const dotenvParseVariables = require('dotenv-parse-variables'); | |
const fs = require('fs'); | |
const chalk = require('chalk'); | |
const envVars = require('dotenv-safe').config({ | |
allowEmptyValues: true | |
}); | |
const parsedVars = dotenvParseVariables(envVars.parsed); | |
function generateDef() { | |
let props = Object.keys(parsedVars) | |
.map(key => { | |
return `${key}: ${typeof parsedVars[key]};` | |
}) | |
.join(" "); | |
const output = `export default class EnvConfig { | |
${props} | |
}\n`; | |
fs.writeFile('./src/environments/env-config.ts', output, (err) => { | |
if (err) { | |
console.log(err); | |
} | |
console.log('Angular environment definition file generated'); | |
}); | |
} | |
function generateConst() { | |
function stringify(obj_from_json) { | |
if (typeof obj_from_json !== "object" || Array.isArray(obj_from_json)) { | |
// not an object, stringify using native function | |
return JSON.stringify(obj_from_json); | |
} | |
// Implements recursive object serialization according to JSON spec | |
// but without quotes around the keys. | |
let props = Object | |
.keys(obj_from_json) | |
.map(key => { | |
return `${key}: ${stringify(obj_from_json[key])}`.replace(/"/g, '\''); | |
}) | |
.join(",\n\t"); | |
return `${props}`; | |
} | |
const output = ` | |
const environment = { | |
/* tslint:disable */ | |
${stringify(parsedVars)} | |
/* tslint:enable */ | |
}; | |
export default environment; | |
`; | |
fs.writeFile('./src/environments/environment.ts', output, (err) => { | |
if (err) { | |
console.log(err); | |
} | |
console.log(chalk.green('Angular environment file generated')); | |
}); | |
} | |
fs.mkdir('./src/environments', (err) => { | |
generateConst(); | |
}); | |
//generateDef(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment