Fixing Angular Error: Unexpected value 'undefined' declared by the module

Symptom:

For a module of yours, you get an error message like this on load:

Error: Unexpected value 'undefined' declared by the module 'MyModule'
    at syntaxError (compiler.js:1021)
    at compiler.js:10623
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (compiler.js:10621)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._loadModules (compiler.js:23876)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndComponents (compiler.js:23857)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler.compileModuleAsync (compiler.js:23817)
    at CompilerImpl.push../node_modules/@angular/platform-browser-dynamic/fesm5/platform-browser-dynamic.js.CompilerImpl.compileModuleAsync (platform-browser-dynamic.js:143)
    at core.js:4999
[...]

Solution

First, try to restart ng serve. In some cases this will outright fix the issue.

The error message is caused by some element of your @NgModule declarations: [ /* ... */ ] to be undefined (… declared by the module in the error message should be taken literally, it’s in the declarations!).

For example, if you have a @NgModule declaration like this:

@NgModule({
  imports: [
    RecallCommonModule,
    CommonModule,
    MyRoutingModule
  ],
  declarations: [,
    MyDetailComponent,
    MySearchComponent
  ],
  providers: []
})

The issue is in the stray comma in the declarations line: When compiled, it results in [undefined, MyDetailComponent, MySearchComponent]. Removing the stray comma fixes the issue.

Another possible cause of this error is if one of the values in declarations is undefined.

For example if you have an import statement like

import { MyComponent } from './my.component';

in your module file, and, for some reason, MyComponent is undefined, this will cause the same error message to appear.

In order to track down which of your components in the declarations array, you could temporarily add a statement like this beforeyour @NgModule :

if(MyComponent === undefined) {
    console.log("MyComponent is undefined!");
}

In case you don’t have any of the issues above, follow the standard procedure: Comment out every element in your declarations array and see which causes the error message to disappear.