Not only the URL but there are some other parameters that need to be taken from environment variables.
Environment variables must be taken and written to environment.ts
before build! because of some Javascript restrictions in accessing filesystem, environment, etc at runtime.
For this, first you need a module for writing environment variables and this module has to be executed with ts-node
in your build
script:
"scripts": {
.....
"config": "ts-node set-env.ts",
"build": "npm run config && ng build",
....
},
and your set-env.ts
file:
var fs = require('fs');
const targetPath = './src/environments/environment.ts';
const colors = require('colors');
require('dotenv').load();
const envConfigFile = `export const environment = {
ENV_VAR_1: '${process.env.var_1}',
ENV_VAR_n: '${process.env.var_n}',
};`;
console.log(colors.magenta('The content of `environment.ts` will be: \n'));
console.log(colors.grey(envConfigFile));
fs.writeFile(targetPath, envConfigFile, function (err) {
if (err) {
throw console.error(err);
} else {
console.log(colors.magenta(`environment.ts file is created`));
}
});
and of course you have to add ts-node
and dotenv
to your dependencies.
and you can easily access variables of environemnt.ts like:
import {environment} from '../environments/environment';
....
var envVar1 = environment.ENV_VAR_1;
Node 12^, Angular 10^, and I didn't check this with older Node/Angular/Typescrip versions