How to read port and host from environment.ts variable for angular.json configuration

3.5k views Asked by At

Is there any way to read post number and host name form environment.ts file and run the ng serve command. My requirement is to use different port and host for Dev, QA and Prod environments.

Now I am manually changing it in angular.json file

"serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "port": 5001 "host":'10.20.45.10' },

I want to read it form environment.ts and environment-prod.ts according to the build

1

There are 1 answers

0
Muhammed Albarmavi On

the environment will be a great place for configuration when the angular app is running ,but in here we try to run the cli based on configuration file , I was looking to set this in the angular.json file but I face dead end , so I go to write a node script will get the configuration from a file then run the cli base of that configuration ,maybe there is a better way but this what we come out with .

I have use here ts-node

run.ts

import { exec } from 'child_process';
import { environment as dev } from './src/environments/environment';
import { environment as prod } from './src/environments/environment.prod';


function run(command: string): void {
    exec(command).stdout.on('data', (data) => {
        console.log(data.toString());
    });
}

const target = process.argv.slice(2)[0] || 'dev';

console.log(` running in => ${target} `);
switch (target) {
    case 'prod': {
        run(`ng s --host ${prod.url} --port ${prod.port} `);
        break;
    }
    default: {
        run(`ng s --host ${dev.url} --port ${dev.port} `);
    }

}

configration file run-tsconfig.json (I have copy this one from tsconfig.json)

   {
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "module": "commonjs",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ]
  }
}

environment.prod.ts

export const environment = {
  production: true,
  url: '127.0.0.1',
  port: 2000
};

environment.ts

export const environment = {
  production: false,
  url: '127.0.0.1',
  port: 3000
};

run the cli serv base of production url

ts-node --project run-tsconfig.json run.ts prod

prod

by default will read the url information from environment.ts (dev)

ts-node --project run-tsconfig.json run.ts

dev