With Appflow, it is possible for builds to be configured with a set of statically defined environment variables through the use of Appflow environments. However depending on your use case, Angular environments may be preferred and it is also possible to use Angular environment files within Appflow.
This article will discuss Angular environments, creating environment variables in Appflow, and consuming variables with scripts during the build. For a full overview of Angular environments, see this documentation.
In this example, two environments will be used, QA and Production. Two custom environment variables are also used, BUILD_ENV and SERVER_URL. To start, these environments are created in Appflow under Builds > Environments:
For this example, the SERVER_URL variable is added to the "/src/environments/environment.ts" and "/src/environments/environment.prod.ts" files. Here is an example:
export const environment = {
production: true,
serverUrl: "$SERVER_URL"
};
Note: Additional environments could also be used such as "/src/environments/environment.staging.ts", "/src/environments/environment.qa.ts" or "/src/environments/environment.anything.ts". The important part for this is to assign the configuration with your build command. With the current example the following could be used for the build script with Appflow:
"build": "ng build --configuration=$BUILD_ENV",
Next, a script is created to consume the SERVER_URL variable. BUILD_ENV will also be used in the script to determine which environment the build is for. Here is an example bash script using envsubst:
#!/bin/bash
if [ "$BUILD_ENV" = "qa" ]; then
envsubst < ./src/environments/environment.ts
else
envsubst < ./src/environments/environment.prod.ts
fi
For the last step, a prebuild npm script is added in the package.json. For this example, the above script is named 'serverurl.sh'. Installing gettext was also needed so that envsubst could be used. Here is what this looks like:
"prebuild": "apt-get update && apt-get -y install jq gettext && sh serverurl.sh",
Now save the commits and test some builds!
Note: The above example is useful specifically for consuming environment variables during the build. If you are instead looking to inject environment variables into your application, this would require a different approach as this is not natively supported in Angular. This article has useful information for this topic if this is necessary for your project. One option to consider is ngx-env.
Comments
0 comments
Article is closed for comments.