Home > Blockchain >  Use different env configs per environment | Angular Typescript
Use different env configs per environment | Angular Typescript

Time:01-12

In Angular, I want to use different env configs per environment.

That means, if I for example deploy to the dev Enviroment, I want the Angular App to use the Dev Variables, and if I deploy to Prod I want Angular to use the prod Variables.

Is there a way to do that? For Example create a file with all the variables and then Angular just has to look in which environmnent it is in and choose the right variable.

CodePudding user response:

just create a new typescript file in project root directory, same directory where pacakage.json file exist, lets say you make a file with name set-env.ts put this code into the file

import { writeFile } from 'fs';
// Configure Angular `environment.ts` file path
const targetPath = './src/environments/environment.ts';
const targetPathProd = './src/environments/environment.prod.ts';
const envConfigFile = `export const environment = {
   production: false,
   serverURL: 'https://devenviroment.com/api',
   someOtherProperty: 'response'
};
`;
const envProdConfigFile = `export const environment = {
   production: true,
   serverURL: 'https://serverurlproduction.com/api',
   someOtherProperty: 'value'
};
`;
console.log('The file `environment.ts` will be written with the following content: \n');
console.log(envConfigFile);
writeFile(targetPath, envConfigFile, function (err) {
  if (err) {
    throw console.error(err);
  } else {
    console.log(`Angular environment.ts file generated correctly at ${targetPath} \n`);
  }
});
writeFile(targetPathProd, envProdConfigFile, function (err) {
  if (err) {
    throw console.error(err);
  } else {
    console.log(`Angular environment.prod.ts file generated correctly at ${targetPath} \n`);
  }
});

Now add this line to package.json file inside scripts tag

"config-env": "ts-node set-env.ts",
"build": "ng build"

Now when you are building your project you can simply use this command

npm run config-env & npm run build

npm run config-env command will overwrite your environment files with configurations that you have written in set-env.ts

CodePudding user response:

Check this -> angular.io/guide/build#configuring-application-environments https://stackoverflow.com/users/9471852/siddhant

  •  Tags:  
  • Related