What is ngcc in Angular Ivy and why is it important?

The ngcc (Angular Compatibility Compiler) is a tool used to compile Angular libraries that have been published in the legacy format, which is not compatible with the Angular Ivy runtime, to a format that is compatible with Ivy.

Before Angular Ivy, the Angular compiler would compile Angular applications and libraries into a single JavaScript file. However, this approach had a number of limitations, including a lack of tree-shaking and inability to use modern JavaScript language features.

With the introduction of Angular Ivy, the compiler was rewritten to generate small, focused files for each Angular component, and to take advantage of modern JavaScript features such as classes, decorators, and type annotations. This allows for faster compilation times, better tree-shaking, and improved debugging.

However, this new approach also means that existing Angular libraries that were published in the old format are not compatible with the Ivy runtime. This is where ngcc comes in.

When building an Angular Ivy project, ngcc will automatically be run on any legacy libraries that are imported. It will compile these libraries to the new format, allowing them to be used in the Ivy project. This allows developers to continue using existing libraries while taking advantage of the benefits of Ivy.

Overall, ngcc is an important tool for Angular developers working with Ivy, as it allows them to use existing libraries while enjoying the benefits of the new Ivy runtime.

Let's take a look at an example of how ngcc is used in an Angular Ivy project:

// In your project's package.json file
{
"dependencies": {
"my-legacy-library": "^1.0.0"
}
}
// In your Angular application
import { MyLegacyComponent } from 'my-legacy-library';
@Component({
selector: 'app-root',
template: `
<my-legacy-component></my-legacy-component>
`
})
export class AppComponent { }

In this example, the my-legacy-library is a library that has been published in the legacy format. When the Angular Ivy compiler encounters this import, it will automatically run ngcc on the library to compile it to the new format, allowing the MyLegacyComponent to be used in the Angular application.

Note that this process happens automatically and does not require any additional configuration on the part of the developer. The Angular Ivy compiler takes care of running ngcc as needed to ensure that legacy libraries are compatible with the Ivy runtime.


May 30, 2022
27078