问题描述
有人知道如何用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.
类似这样的东西:
export const environment = {
production: false,
baseHref: '/'
};
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/">
.
我想也许我是否将我的环境变量命名为与构建命令,cli可能会拾取它,但那里也没有骰子.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!