Skip to content

Instantly share code, notes, and snippets.

@kasir-barati
Last active June 20, 2022 14:50
Show Gist options
  • Save kasir-barati/f3168e18c1dd64e24a7308c4764dc8eb to your computer and use it in GitHub Desktop.
Save kasir-barati/f3168e18c1dd64e24a7308c4764dc8eb to your computer and use it in GitHub Desktop.
A simple script to emerges environment.ts file from .env file for an Angular app.

Some good notes:

  • With Angular you can store those information in the environment.ts files, but you need to commit them in the repository, and again, this is not what we want. If something is changing, you need to update them and in an Agile environment, you also need to pass Code Review, Test and many other steps to certify a “Done” ticket.
  • Keep in mind that in a Front End world, it is pretty much impossible to keep anything hidden from the final user (the code can always be inspected in any browser). For this reason, the use of secret keys and passwords in this world have to be considered very carefully and under a secure structure managed backend side.

Important possible improvements:

Please note that this script disclose too much data. You can filter them by using filter-env lib. In that case you can add a specific prefix to all of your envs. The other point is that this script uses the same env name as it is inside the .env file, so my suggestion to you is to use a more normal naming. Another note is that you have to define an interface to be typed while working with environment.ts

References:

import { writeFileSync } from "fs";
import { config } from "dotenv";
// Configure Angular `environment.ts` file path
// const targetPath = process.argv[2];
const targetPath = "./src/environments/environment.ts";
// Load node modules
config();
// `environment.ts` file structure
let envConfigFile = "export const environment = {";
for (const [key, value] of Object.entries(process.env)) {
envConfigFile = envConfigFile.concat(`${key}: '${value}',`);
}
envConfigFile = envConfigFile.concat("};");
console.log("Auto generated environment.ts");
console.log(envConfigFile);
writeFileSync(targetPath, envConfigFile, { encoding: "utf-8" });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment