2

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

Spy1984
  • 89
  • 3
  • 12
  • You can create your own environments inside your environment folder and mansion that environment file inside `angular.json` or `angular-cli.json`. For the production you can use that environment setting. – Shashikant Devani Sep 17 '19 at 07:26
  • @Shashikant but we cant read the port and host variable in the environment.ts file into json file right? My requirement is to run app with the port specified in the environment.ts file – Spy1984 Sep 17 '19 at 10:38
  • the only solution I think of is to use node to run the cli then we can pass the parameter from environment check my answer , hope this will help – Muhammed Albarmavi Sep 17 '19 at 12:43

1 Answers1

3

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

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91