0

I want to set some of environment variable with npm start command some thing like npm start apiUrl=http://localhost:5000. I want the values of these variables to set properties inside my environment.ts

I have very basic knowledge of node thus my question may not be correct.

I have installed dotenv and my package.json is:

{
  "name": "####",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "config": "ts-node set-env.ts",
    "start": "npm run config && ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "server": "npm run config && ng serve --port $PORT"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~10.0.4",
    "@angular/common": "~10.0.4",
    "@angular/compiler": "~10.0.4",
    "@angular/core": "~10.0.4",
    "@angular/forms": "~10.0.4",
    "@angular/platform-browser": "~10.0.4",
    "@angular/platform-browser-dynamic": "~10.0.4",
    "@angular/router": "~10.0.4",
    "bootstrap": "^3.4.1",
    "dotenv": "^8.2.0",
    "named-regexp-groups": "^1.0.5",
    "rxjs": "~6.6.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.3"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.1000.3",
    "@angular/cli": "^10.0.3",
    "@angular/compiler-cli": "~10.0.4",
    "@angular/language-service": "~10.0.4",
    "@babel/plugin-transform-named-capturing-groups-regex": "^7.8.3",
    "@types/crypto-js": "^3.1.43",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.9.7"
  }
}

Update

This is the set-env.ts file. I have wrote to update my environment.ts file, but as I have mentioned above I couldn't find any solution to update process.env properties with commands .

 const fs = require('fs');

const defaultEnvironmentFile = require('./src/environments/environment.default.ts');

const writeFile = fs.writeFile;

const targetPath = './src/environments/environment.ts';
const sourcePath = './src/environments/environment.default.ts';
require('dotenv').config();

let content = [];

for (let key in defaultEnvironmentFile) {
    if (process.env[key] !== undefined) {
        if (typeof defaultEnvironmentFile[key] === 'string') {
            content.push(`'${key}: ${process.env[key]}'`);
        }
        else {
            content.push(`${key}: ${process.env[key]}`);
        }
    }
    else {
        if (typeof defaultEnvironmentFile[key] === 'string') {
            content.push(`${key}: '${defaultEnvironmentFile[key]}'`);
        }
        else {
            content.push(`${key}: ${defaultEnvironmentFile[key]}`);
        }
    }

}

let runtimeEnvironment = `export const environment = { \r\n\t${content.join(',\r\n\t')}\r\n};`;

writeFile(targetPath, runtimeEnvironment, function (err) {
    if (err) {
        throw console.error(err);
    }
});
Hamed Mahdizadeh
  • 936
  • 1
  • 15
  • 29
  • 1
    Does this answer your question? [Use process.env in Angular 5 environment](https://stackoverflow.com/questions/49496438/use-process-env-in-angular-5-environment) – critrange Jul 26 '20 at 02:39
  • Thank you @yash The question tells the same thing that I want, but no one has answered how to dynamically set .env variable in command line. – Hamed Mahdizadeh Jul 26 '20 at 06:20

1 Answers1

0

This can be done by using a custom webpack builder and invoking ng serve as a child process and passing in the environment variables to the child process.

Here is a step by step guide which explains how to accomplish this:

import * as yargs from 'yargs';
import { spawn } from 'child_process';
import { DEFAULT_APP_ENV } from './app-env';

const parseNgArgs = () => process.argv.filter((arg, index) => index > 1 && Object.keys(DEFAULT_APP_ENV).every(key => !arg.includes(key)));

const ngArgs = parseNgArgs();

const argv = { ...DEFAULT_APP_ENV, ...yargs.argv};

const childProcess = spawn('yarn', ['start', ...ngArgs], {
  stdio: 'inherit',
  env: { ...process.env, APP_ENV: JSON.stringify(argv) },
  shell: true,
});

Using this you can pass in any command-line environment variables like this and access them at runtime in your Angular

yarn serve --logErrors --no-runtimeChecks --loggerHost="http://localhost:6000"
Nivrith
  • 21
  • 2