Angular CLI supports const environment but you need to
compile the project for each environment. But the IT guys don’t want to run again and again the CLI for each environment.
The recipe:
1.
const config = {
url : 'http://www.ynet.co.il'
}
2. Add the file to index.html, like this.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Webconfig</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <script src="assets/config.js"></script> </head> <body> <app-root></app-root> </body> </html>
3. Now you can use the config variable everywhere.
Example:
import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; declare let config:{url:string}; if (environment.production) { enableProdMode(); } console.log(`config url : ${config.url}`); platformBrowserDynamic() .bootstrapModule(AppModule) .catch(err => console.log(err));
Impotent: Don’t import the config.js like this: import {config} from './assets/config.js'; Because it will insert the file to the bundles files that CLI creates.
What you think?
Tzach Ovadia
אוקטובר 23, 2017 at 5:50 am
Hi Eyal,
In you opinion – which is a better practice for frontend apps – build for each environment or build once deploy many?
eyal.vardi
אוקטובר 24, 2017 at 10:29 am
יותר בטוח לבנות גירסה לכל סביבה, אך זה יותר עבודה ופחות דינאמי (זה הסיבה שזה יותר אמין).
אך יש מצבים שהנוקשות הזאת לא מתאימה.