I have an angular 9 application in which I read the api url from an assets folder:
@Injectable()
export class ConfigService {
private configUrl = '../../../assets/config/config.json';
constructor(private loggerService: LoggerService) { }
public async loadConfig(): Promise<any> {
try {
const response = await fetch(this.configUrl);
if (!response.ok) {
throw new Error(response.statusText);
}
return await response.json();
} catch (err) {
this.loggerService.error(`ConfigService 'loadConfig' threw an error on calling ${this.configUrl} : ${err.tostring()}`);
}
}
}
Method used for reading configuration file is described in Configuring angular production files after build.
environment.ts
is
export const environment = {
production: false,
apiUrl: "https://localhost/api/",
};
environment.prod.ts
is
export const environment = {
production: true,
apiUrl: "https://server/api/",
};
config.json
is
{
"apiUrl": "http://someTestServer/api/"
}
The incomplete script to copy apiUrl
to config.json
var fs = require("fs");
fs.readFile(`./src/environments/environment.${process.env.CONFIG}.ts`, 'utf8', function (err, data) {
fs.writeFile('./src/assets/config/config.json', data, function (err) {
if (err) throw err;
console.log('complete');
});
});
My script section of package.json looks like following:
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"build-test": "CONFIG=test node update-config.js && npm run build",
"build-prod": "CONFIG=prod node update-config.js && npm run predeploy",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"predeploy": "ng build --prod",
"deploy": "node ftpdeploy.js"
}
Considering above: How can I automatically populate the contents of my config.json
file based on different environment variable prior build so I don't need to manually copy and paste a json file to the \dist
folder?
Update 1: Now I can copy the contents of my enviroment.xxx.ts into the config.json file. There is one problem remaining: When I copy the contents from environment.xxx.ts it copies the entire contents of environment.xxx.ts into the config.json (It also copies the import section of my enviroment.xxx.ts) however the expected result is to read the environment
(export const environment
) into an object and update the config.json according to the source environment
object. How can I achieve this?