使用ng build从环境变量设置基本href [英] Set base href from an environment variable with ng build

查看:359
本文介绍了使用ng build从环境变量设置基本href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何用angular-cli做到这一点吗?我希望能够将baseHref路径存储在/src/environments/environment.x.ts内的环境变量中,并基于构建期间选择的环境,能够设置baseHref路径.

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.

类似这样的东西:

environment.ts

environment.ts

export const environment = {
  production: false,
  baseHref: '/'
};

environment.prod.ts

environment.prod.ts

export const environment = {
  production: true,
  baseHref: '/my-app/'
};

然后致电...

ng build --prod

...并使我的/dist/index.html文件显示为<base href="/my-app/">.

...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.

是否有某种方式可以从命令行引用环境变量? ng build --base-href environment.baseHref之类的东西?

Is there someway to reference an environment variable from the command line? Something like ng build --base-href environment.baseHref?

推荐答案

您将不得不使用APP_BASE_HREF

@NgModule({
  providers: [{provide: APP_BASE_HREF, useValue: environment.baseHref }]
})
class AppModule {}

请参见角度文档

编辑

由于CSS/JS不适用于APP_BASE_HREF,因此您可以执行以下操作:

Since CSS/JS does not work with APP_BASE_HREF, you can do this:

app.component.ts 中,通过import {DOCUMENT} from "@angular/platform-browser";

constructor(@Inject(DOCUMENT) private document) {
}

然后在您的ngOnInit()

ngOnInit(): void {
    let bases = this.document.getElementsByTagName('base');

    if (bases.length > 0) {
      bases[0].setAttribute('href', environment.baseHref);

    }
  }

这篇关于使用ng build从环境变量设置基本href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆