A value 'window' cannot be determined statically

Viewed 779

In my Angular 12 app I have a module like

@NgModule({
  imports:      [ window.config.myConfXY ? ModuleX : ModuleY ],
  providers:    [ ... ],
  declarations: [ ]
})
export class AppModule { }

but the compiler complains with: "A value for 'window' cannot be determined statically, as it is an external declaration."

I am trying to deploy the app in an nginx container passing in some environment variables. A generated "env.js" is referenced in index.html and defines the window.config.

What does the error mean and how can I fix that? Unfortunately, I found nothing useful regarding the error description on the web.

1 Answers

As per my understanding, this is not possible.

The Angular compiler needs to evaluate the NgModule imports during the build time itself i.e it needs to statically evaluate the conditions. It needs to know the value during the compilation and cannot wait to evaluate these until runtime. There is no way for the compiler to know about window object values during the compile time.

Considering we are not declaring window object ourselves within the application and Angular not being able to determine its value at compile time, hence the below error:

A value for 'window' cannot be determined statically, as it is an external declaration.

One possible solution would be to make use of the environment files. We have fileReplacements in angular.json file and so we can define a config property within an environment file. Since we can have multiple files based on the different environments, during the build the compiler should be able to evaluate the environment config property value statically.

Resources:

Related