Angular environment files allow you to have separate configurations for different build targets. However, our CI/CD (Jenkins) is not set-up to facilitate different target builds. We would rather fill the target specific information using docker environment variables. To achieve this, an environment variables substitution when creating the container is necessary. This can only be done on files that are physically available in the target folder of our angular project. Environment files are not, because they get baked into the application and a trace of the variable to substitute cannot be found anymore.
The solution
Next to the environment
folder there is also a config
folder. This folder contains a config.js
file, where you can place local used environment variables. The other file is config.template.js
, you can use this file to insert the same variables, but with a value that can be substituted with envsubst
. These files are treated as assets, meaning they are statically served. There is also a typescript interface to add typing to these files.
space-app-angular
├── src
. ├── environment
├── config
. ├── config.js
└── config.template.js
- config.js
- config.template.js
- config.interface.ts
- http.service.ts
- entrypoint.sh
__config = {
baseUrl: 'http://localhost:8080',
// @anchor:properties:start
// @anchor:properties:end
// anchor:custom-properties:start
// anchor:custom-properties:end
}
__config = {
baseUrl: '${BACKEND_API_BASE_URL}',
// @anchor:properties:start
// @anchor:properties:end
// anchor:custom-properties:start
// anchor:custom-properties:end
}
export interface Config {
baseUrl: string;
// @anchor:properties:start
// @anchor:properties:end
// anchor:custom-properties:start
// anchor:custom-properties:end
}
import {Config} from '~core/models/config.interface';
declare let __config: Config;
...
get baseUrl() {
return `${__config.baseUrl}/spaceApp`
}
#!/bin/bash
# Replace environment variables in config files
for FILE in /app/config/*; do echo "$(envsubst < $FILE)" > $FILE; done;
mv /app/config/config.template.js /app/config/config.js
echo "Starting Nginx"
nginx -g 'daemon off;'