Does anyone know how to accomplish this with the angular-cli? I would like to be able to store the baseHref
path in an environment variable within /src/environments/environment.x.ts
and based on the selected evironment during build, be able to set the baseHref path.
Something like this:
environment.ts
export const environment = {
production: false,
baseHref: '/'
};
environment.prod.ts
export const environment = {
production: true,
baseHref: '/my-app/'
};
And then call...
ng build --prod
...and have my /dist/index.html
file show <base href="/my-app/">
.
I thought maybe if I named my environment variable the same as the --base-href
build option used in the build command that the cli might pick it up, but no dice there either.
Is there someway to reference an environment variable from the command line? Something like ng build --base-href environment.baseHref
?
You would have to use APP_BASE_HREF
@NgModule({
providers: [{provide: APP_BASE_HREF, useValue: environment.baseHref }]
})
class AppModule {}
See angular doc
EDIT
Since CSS/JS does not work with APP_BASE_HREF, you can do this:
In app.component.ts, inject DOCUMENT via import {DOCUMENT} from "@angular/platform-browser";
constructor(@Inject(DOCUMENT) private document) {
}
Then on your ngOnInit()
ngOnInit(): void {
let bases = this.document.getElementsByTagName('base');
if (bases.length > 0) {
bases[0].setAttribute('href', environment.baseHref);
}
}
You need editing angular.json
for production environment. Replace __BASE_HREF__
and __DEPLOY_URL__
constant with your desired path and enjoy.
"configurations": {
"production": {
"baseHref": "__BASE_HREF__",
"deployUrl": "__DEPLOY_URL__",
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
Read about baseHref
and deployUrl
in https://angular.io/cli/serve
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With