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

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

问题描述

有谁知道如何用 angular-cli 完成这个任务?我希望能够将 baseHref 路径存储在 /src/environments/environment.x.ts 内的环境变量中,并基于构建期间选择的环境,是能够设置baseHref路径.

像这样:

<块引用>

环境.ts

export const environment = {生产:假,baseHref: '/'};

<块引用>

environment.prod.ts

export const environment = {生产:真实,baseHref: '/my-app/'};

然后调用...

ng build --prod

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

我想也许如果我将环境变量命名为与 build command cli 可能会捡起它,但那里也没有骰子.

有没有办法从命令行引用环境变量?类似于 ng build --base-href environment.baseHref?

解决方案

您将不得不使用 APP_BASE_HREF

@NgModule({提供者:[{提供:APP_BASE_HREF,useValue:environment.baseHref}]})类 AppModule {}

参见角度文档

编辑

由于 CSS/JS 不适用于 APP_BASE_HREF,您可以这样做:

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

constructor(@Inject(DOCUMENT) 私有文档) {}

然后在你的 ngOnInit()

ngOnInit(): void {let bases = this.document.getElementsByTagName('base');如果(bases.length > 0){bases[0].setAttribute('href', environment.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.

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

    }
  }

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

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