Set base href from an environment variable with ng build

30,340

Solution 1

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);

    }
  }

Solution 2

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

Share:
30,340
ryanulit
Author by

ryanulit

Updated on April 11, 2021

Comments

  • ryanulit
    ryanulit about 3 years

    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?