Problem with NGCC

NGCC stands for Angular Compatibility Compiler, which recompiles various npm packages to Ivy format. Most of the time it “just works”, expect when it does not.

There are configuration options for ngcc, which you can specify in ngcc.config.js file in root folder of your project. But sometimes this seems not enough. Sometimes the same code may trigger the error, while when used in different context it works ok.

Consider this example:

{ provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: { verticalPosition: 'top' } }

When used in the main app.module.ts file, it will trigger error similar to the one below. But if used in a sub module file, which is loaded later, it compiles without difficulties.

So remember, when you see error related to ngcc, check your main module and submodule files. You may need to declare some providers repeatedly in the submodules.

Problem with providedIn: root

Problem with dependency on Angular Material may also happen when some class in lazy-loaded module is annotated with @Injectable({providedIn: 'root'}). Then those Material dependencies have to be declared in root app.module.ts. But I could not use that, as it caused other problems in our solution.

Using providedIn: 'any' helped. It may not be the ideal solution, because it may lead to having multiple instances of the same module, instead of singletons. So there are definitely cases when you absolute do not want to use it, for examples for Stores.

Unused imports

Interestingly, when there is a forgotten import it may affect the build in CI/CD pipeline. The import should have been tree-shaken away. But for some not-obvious reason, the pipeline sometimes does not remove the import, which results in a build crashing, while it passes ok locally.

And yes, I am going to fix this with Husky pre-commit hooks, but that is not yet ready at the time of writing.

Happy coding.

———————————————————-

Error: Tried to overwrite /opt/rb3/node_modules/.pnpm/@angular+material@11.2.13_83d90f83a63ec4f36f90a5e25a1aad3a/node_modules/@angular/animations/animations.d.ts.__ivy_ngcc_bak with an ngcc back up file, which is disallowed.
at NewEntryPointFileWriter.InPlaceFileWriter.writeFileAndBackup (/opt/rb3/node_modules/.pnpm/@angular+compiler-cli@11.2.14_d7da94ea75fca089b21302a3a7dac349/node_modules/@angular/compiler-cli/ngcc/src/writing/in_place_file_writer.js:58:27)

headscratcher