Angular 应用的编译时与运行时配置

2025-06-08

Angular 应用的编译时与运行时配置

当你开发一个大型应用程序时,很可能需要进行某种配置。这些配置可能包括简单地显示应用版本号,也可能包括注入自定义主题等等。在 Angular 中,有两种不同的配置方式:编译时配置和运行时配置。让我们分别来了解一下这两种配置。

编译时配置

(点击打开 Egghead 课程)

什么是编译时配置?它的基本含义是,在编译和打包应用程序时,将配置编译到应用程序中。如果您使用的是 Angular CLI,则已经有一个预配置的设置,其中包含此类编译时配置选项。

文件夹内environments有一个environment.tsenvironment.prod.ts文件。

// environment.ts
export const environment = {
  production: false
};
Enter fullscreen mode Exit fullscreen mode
// environment.prod.ts
export const environment = {
  production: true
};
Enter fullscreen mode Exit fullscreen mode

由于这些只是普通的 JavaScript 对象,因此您可以在其上添加特定于环境的属性。负责引导 Angular 应用程序的

默认main.ts文件会使用这些环境文件来判断应用程序是否处于生产模式,以便应用一些运行时优化,例如调用enableProdMode()

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));
Enter fullscreen mode Exit fullscreen mode

您只需将其导入文件即可任意获取该environment对象的引用。environment.ts

import { environment } from '../environment/environment';

// do something meaningful with `environment`
console.log(environment);
Enter fullscreen mode Exit fullscreen mode

注意,我们总是导入 ,environment.ts而不是导入特定于环境的文件,例如environment.prod.ts。原因是在编译时,Angular CLI 会负责将特定于环境的配置文件重命名为environment.ts,并将其编译到你的应用中。

您还可以创建新文件,例如用于“暂存”环境的文件。只需创建一个新文件environment.staging.ts并确保在angular.json文件中进行配置即可:

{
  // ...
  "projects": {
    "demo": {
      //...
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          // ...
          "configurations": {
            "staging": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.staging.ts"
                }
              ],
              //...
            },
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              //...
            }
          }
        },
        //...
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

最后,我们需要告诉 CLI 我们正在为哪个环境构建,以便它能够获取正确的配置文件。这发生在我们的脚本部分package.json

{
  ...
  "scripts": {
    "ng": "ng",
    "build": "ng build --prod",
    "build:staging": "ng build --prod --env=staging"
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode

注意,我们传入了--env=<your-environment>标志。这--prod是一个内置命令,如果没有特别指定,它会自动使用生产配置。此外,它还启用了 AOT 编译

运行时配置

(点击打开 Egghead 课程)

但是,如果您需要更改应用的配置设置,或者甚至希望通过 API 公开这些设置,那么您需要使用运行时配置方法。通常,您只需一个 JSON 文件,appConfig.json其中包含必要的配置选项,然后将其与应用一起部署到服务器上。应用运行时,您会向该 JSON 文件执行 HTTP 请求并读取其中的设置。

然而,你想要的是仅在设置加载并应用后才启动应用。一个简单的方法可能是这样的。在你的app.component.ts项目中,只需添加一个*ngIf守卫:

@Component({
    selector: 'app-root',
    template: `
        <div *ngIf="configLoaded">

        </div>
    `
})
export class AppComponent implements OnInit {
    configLoaded = false;

    ngOnInit() {
        this.http.get('./assets/appConfig.json')
            .subscribe(config => {
                // do something with your configuration
                ...

                this.configLoaded = true;
            });
    }
}
Enter fullscreen mode Exit fullscreen mode

这样,除非configLoaded为真,否则其他组件将无法启动,因此<div>才会显示。

虽然这样可行,但还有一种更优雅的方法:我们可以通过使用APP_INITIALIZER令牌来进入 Angular 的引导阶段。首先,我们创建一个 Angular 服务来处理远程配置的获取……

阅读更多 ”

鏂囩珷鏉ユ簮锛�https://dev.to/angular/compile-time-vs-runtime-configuration-of-your-angular-app-15f2
PREV
Decorators do not work as you might expect 🤔 Quick Recap on Decorators The @Clamp Decorator Exploring decorators under the hood The Problem Creating instance-targeted decorators Bonus Conclusion Special Thanks
NEXT
Angular:Setters 与 ngOnChanges - 哪一个更好?