Everything you need to know about the Angular Compatibility Compiler(ngcc)
Tags: angular, webdev, typescript, javascript
Published: 2020-05-16 08:27:33

In a previous article, I wrote about `ngtsc` Angular latest compiler. Today we're going to talk about the Angular Compatability Compiler(ngcc). 

In that article, I talked about how angular compiles the code in the latest version(v9) but think about it, not all code is compiled at the same time there are libraries, npm modules, there dependencies are precompiled and these may no work well with the way `ngtsc` compiles Angular code. This may cause failures at runtime, compile-time, etc.  Fortunately, the Angular has already solved these problems for us using the Angular compatibility compiler `ngcc`.

## What is ngcc??

Let us first see it from Angular glossary.

> Angular compatibility compiler. If you build your app using Ivy, but it depends on libraries that have not been compiled with Ivy, the CLI uses `ngcc` to automatically update the dependent libraries to use Ivy.

As many of already know that Angular changed its default compiler for View Engine to Ivy in version 9. Most of the code generated by Ivy is very different from the code generated by View Engine. So, code generated by the View Engine compiler cannot be consumed by the Ivy compile but this creates a huge problem that most of the libraries and components of Angular are generated using the View Engine compiler. If we don't make these compatible a huge chunk of community wor will be rendered useless. So, to get out of this problem Angular team created a compatibility compiler `ngcc`. It makes View engine code compatible with the Ivy. I am really thankful for this tool.

## How ngcc works?

The ngcc compiler parses the precompiled JavaScript code which is  produced by the ViewEngine compiler, for components, directives, pipes, injectables, etc. It then updates that code so that it is as though it had been originally compiled by the Ivy compiler.

It modifies all the formats of JavaScript that are needed in te app, e.g. ES2015, ES5, UMD, etc. After  that it updates the typing file, since these are needed for the Ivy compiler to process the application source files.

ngcc mostly runs from a postinstall hook in your package.json file:

```
{
  "scripts": {
    "postinstall": "ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points"
  }
}
```
The postinstall script will run on every installation of node_modules, including those performed by ng update and ng add.

If you perform multiple installs in a row, this can end up being slower than letting Angular CLI run ngcc on builds.

### Operations done by ngcc

1. Scan the `node_modules` for packages that are in APF[Angular package format](https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs/mobilebasic) by checking `.metadata.json` files. (It just checks for their existence to determine whether a package is an Angular package or not.).
1. Produce Ivy compatible versions for each of these packages

To generate Ivy compatible versions `ngcc`  creates `__ivy_ngcc__` sub-directories inside each package that it compiles if called with the --create-ivy-entry-points option (which is how the CLI calls it). The other "mode" of operation (without the --create-ivy-entry-points option) - which is the default behavior if you call ngcc manually - updates the files in place.

## Configuring ngcc

`ngcc` is by defalt able to work out how to compile any package. But occasionally there may be packages that deviate too far from default Packages [APF](https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs/mobilebasic) style.

In these kind of cases also it is possible to provide configuration to modify how ngcc views specific entry-points to packages so that it is able to process them.

### package/entry-point configuration

Entry-points to a package are configured using a configuration file `ngcc.config.js`

``` js

module.exports = {
  packages: {
    'package-name': {
      entryPoints: { ... }
    },
    ...
  }
};

```
In these files `entryPoints` is a property whose keys are the paths to the entry-point (relative to the package). For example:

```json

entryPoints: {
  // the primary (root) entry-point
  '.': { ... },
  // a secondary entry-point
  './testing': { ... },
}

```
Let us now discuss entry points in detail:

By default entry point uses the following [interface](https://github.com/angular/angular/blob/4d0e175a6544e7f418b505f83157c894818f37fd/packages/compiler-cli/ngcc/src/packages/configuration.ts#L71)

```ts
interface NgccEntryPointConfig {
  ignore?: boolean;  
  override?: PackageJsonFormatPropertiesMap;   
  ignoreMissingDependencies?: boolean;
  generateDeepReexports?: boolean;
}
```

Let us now discuss each of these properties in detail

1. ignore - If true it does not process (or even acknowledge the existence of) this entry-point
2. override - This property, if provided, holds values that will override equivalent properties in an entry-point’s package.json file.
3. ignoreMissingDependencies - `ngcc` genrally skips compilation of entrypoints that contain imports that can’t be resolved or understood. If this option is specified, ngcc will proceed with compiling the entrypoint even if thre are such missing dependencies.
4. generateDeepReexports - Enabling this option for an entrypoint tells ngcc that deep imports might be used for the files it contains, and that it should generate private re-exports alongside the NgModule of all the directives/pipes it makes available in support of those imports.

> All the above properties are optional. We can even pass an empty object. The mere existence of an entry-point configuration object tells ngcc that this really is an entry-point that should be processed even if it is missing necessary files, such as a metadata.json file.

## Configuration levels

ngcc Configuration can be done at various levels. The configuration for an entry-point at one of the levels below will override the levels below it.

There are three types of levels on which ngcc runs:

- project level
- package level
- default level

### project level

You can configure ngcc for all the packages that your project uses by placing an ngcc.config.js file at the root of the project next to your package.json file. In this case the developer provides a configuration that fixes issues specific to the libraries used in their application. 

In this case the file may configure multiple packages so the export from the file is an object that has a packages property, which itself is an object where each key is the name of the package being configured.

For example:

```js 

module.exports = {
  packages: {
    "ng2-dragula": {
      entryPoints: {
        "./dist": {
          "ignore": true
        },
        ...
      }
    },
    "other": {
      entryPoints: {
        ... 
      }
    },
    ...
  }

```

Like if all the packages does not have any `.metadata.json` files in the root directory but only inside `dist/`. Without config, ngcc does not realize this is a ViewEngine-built Angular package that needs to be compiled to Ivy.

### Package level

A package author may provide specific configuration to allow ngcc to be able to process entry-points in their package. The configuration at this level is provided in an ngcc.config.js file at the root of the package, next to its own package.json file.

In this case the export from the file is an object that only describes the package being configured, and so will not contain the packages property. For example:

```js
module.exports = {
  entryPoints: {
    "./inputtext": {
      "typings": "./inputtext.d.ts",
      "main": "./inputtest.js"
    },
    "./button": {
      "typings": "./button.d.ts",
      "main": "./button.js"
    },
    ...
  }
};
```

### Default Level

The default configuration for ngcc.

This is the ultimate fallback configuration that ngcc will use if there is no configuration for a package at the package level or project level.

This configuration is for packages that are "dead" - i.e. no longer maintained and so are unlikely to be fixed to work with ngcc, nor provide a package level config of their own.

The fallback process for looking up configuration is:

Project -> Package -> Default

If a package provides its own configuration then that would override this default one.

Also application developers can always provide configuration at their project level which will override everything else.

Note that the fallback is package based not entry-point based.
For example, if a there is configuration for a package at the project level this will replace all entry-point configurations that may have been provided in the package level or default level configurations, even if the project level configuration does not provide for a given entry-point.

### Running ngcc manually

Mosty cli does all the heavy lifting for us while using ngcc but if for some reason you need to run ngcc manually you can do that too.

ngcc can be found in the node_modules binary folder so either of the following commands would work:yarn ngcc/npm run ngcc or node_modules/.bin/ngcc. ots of options are available in ngcc I've extracted them using ngcc --help I have added them below for reference

```
Options:
  --version                          Show version number               [boolean]
  -s, --source                       A path (relative to the working directory)
                                     of the `node_modules` folder to process.
                                                     [default: "./node_modules"]
  -p, --properties                   An array of names of properties in
                                     package.json to compile (e.g. `module` or
                                     `es2015`)
                                     Each of these properties should hold the
                                     path to a bundle-format.
                                     If provided, only the specified properties
                                     are considered for processing.
                                     If not provided, all the supported format
                                     properties (e.g. fesm2015, fesm5, es2015,
                                     esm2015, esm5, main, module) in the
                                     package.json are considered.        [array]
  -t, --target                       A relative path (from the `source` path) to
                                     a single entry-point to process (plus its
                                     dependencies).
                                     If this property is provided then
                                     `error-on-failed-entry-point` is forced to
                                     true
  --first-only                       If specified then only the first matching
                                     package.json property will be compiled.
                                                                       [boolean]
  --create-ivy-entry-points          If specified then new `*_ivy_ngcc`
                                     entry-points will be added to package.json
                                     rather than modifying the ones in-place.
                                     For this to work you need to have custom
                                     resolution set up (e.g. in webpack) to look
                                     for these new entry-points.
                                     The Angular CLI does this already, so it is
                                     safe to use this option if the project is
                                     being built via the CLI.          [boolean]
  --legacy-message-ids               Render `$localize` messages with legacy
                                     format ids.
                                     The default value is `true`. Only set this
                                     to `false` if you do not want legacy
                                     message ids to
                                     be rendered. For example, if you are not
                                     using legacy message ids in your
                                     translation files
                                     AND are not doing compile-time inlining of
                                     translations, in which case the extra
                                     message ids
                                     would add unwanted size to the final source
                                     bundle.
                                     It is safe to leave this set to true if you
                                     are doing compile-time inlining because the
                                     extra
                                     legacy message ids will all be stripped
                                     during translation.
                                                       [boolean] [default: true]
  --async                            Whether to compile asynchronously. This is
                                     enabled by default as it allows
                                     compilations to be parallelized.
                                     Disabling asynchronous compilation may be
                                     useful for debugging.
                                                       [boolean] [default: true]
  -l, --loglevel                     The lowest severity logging message that
                                     should be output.
                                     [choices: "debug", "info", "warn", "error"]
  --invalidate-entry-point-manifest  If this is set then ngcc will not read an
                                     entry-point manifest file from disk.
                                     Instead it will walk the directory tree as
                                     normal looking for entry-points, and then
                                     write a new manifest file.
                                                      [boolean] [default: false]
  --error-on-failed-entry-point      Set this option in order to terminate
                                     immediately with an error code if an
                                     entry-point fails to be processed.
                                     If `-t`/`--target` is provided then this
                                     property is always true and cannot be
                                     changed. Otherwise the default is false.
                                     When set to false, ngcc will continue to
                                     process entry-points after a failure. In
                                     which case it will log an error and resume
                                     processing other entry-points.
                                                      [boolean] [default: false]
  --tsconfig                         A path to a tsconfig.json file that will be
                                     used to configure the Angular compiler and
                                     module resolution used by ngcc.
                                     If not provided, ngcc will attempt to read
                                     a `tsconfig.json` file from the folder
                                     above that given by the `-s` option.
                                     Set to false (via `--no-tsconfig`) if you
                                     do not want ngcc to use any `tsconfig.json`
                                     file.                              [string]
  --help                             Show help
```