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);
}
});