30
votes

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?

2
Why do you want the base href in the environment file? The base href in index.html can be configured with --base-href your-url - shusson
Because I need to run this on a build server with multiple, different deployment locations, and it makes sense to leverage the built-in functionality that angular provides (if possible). - ryanulit

2 Answers

24
votes

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

    }
  }
4
votes

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