Handling Multi-Environment
Hi Friends, This is Lakshman here.
As part of the Series "Angular Best Practices".
Today, We will go through Practices to followed on Handling Multi-Environment for Angular App.
In all command, request to use Angular CLI installed in App's Dev Dependencies.
In package.json
"scripts": {
"ng": "ng",
...
},
"devDependencies": {
...
"@angular/cli": "~10.0.6",
...
},
...
Angular Environments
As Default, The Angular creates environment.ts & environment.prod.ts files to Handle Environments.
Usual Environment variables are,
- Production Flag.
- API Url, etc.,
If we have more than Two Environments such as QA, UAT, we usually create environment.qa.ts & environment.uat.ts and configure variables.
The Current problems were,
- We are needed to create each file per environment, which drives to rebuild application per environment.
- Can't able to Change variables While App Deployment.
- Our API Url's & Other Configuration stuck inside Code Repos.
- Can't Implement CI/CD Pipeline very Fluent.
Things to do
We are required to build Angular Application once and Deploy with environment-specific configuration.
The things to do are,
- Required to Remove Environment Specific variables outside source.
- Handle as Environment on JSON Files instead of environment.{env}.ts File.
How to do it,
It has a various approach for handling multi-environment,
My Approach,
In Any Terminal:
First Create an App Config Service as below,
npm run ng generate service appConfig
The Purpose of the Service is fetching JSON file located in the assets folder and update the Environment variables.
With this option, we can change the JSON file after deployment.
After Service created, Add to Provider with APP_INITIALIZER as below
providers: [
{
provide: APP_INITIALIZER,
useFactory: initConfig,
deps: [ AppConfigService ],
multi: true
}
]
Check out the App Config Service Code in here
Check out the App Module Code in here
Benefits,
- Build Only your Angular App.
- Can Change Environment on Deploy.
- Save Our Time in Build.
If you want to know by Video Check this 12 Factor App in Angular
To Generate the JSON File via NPM Package @lazh/Config Check this Out Here
You may also access to updated source on GitHub by Click Here
On-road head, we will discuss a lot of things.
Looking forward to your comments and share your feedback.
Until that, I am Lakshman, Signing Off.
Comments
Post a Comment