All About Angular Engine Ivy in 5 mins

    Wednesday, February 17, 202118 min read58162 views
    All About Angular Engine Ivy in 5 mins


    Angular is arguably the most popular open-source web app framework which is widely used by developers across the globe. Today, developers in large numbers use Angular. The community of developers using Angular is always waiting for all the periodic updates that Angular comes up with. 

    In 2016, when Google released Angular, many developers migrated to this robust framework. The rapidly growing community looks forward to the Angular team for regular updates, and Angular 8.0 is the upcoming upgrade with a new renderer – Ivy. In this blog, we will go through the definition, concept and features of IVY. 

    The performance of the Angular runtime is quite good but the loading time is longer because of the large file size which affects the overall performance of the application. This is where IVY comes into the scene. Let's learn more:

    What is IVY? 

    Ivy is the pipeline of rendering and compilation of the next-generation. It is very advanced and offers advanced features that were not available before. The speed provided by it is amazing. The loading is very fast even in the networks that are slow. It is very simple to use without any complications. The bundle size is also reduced with its help. It was first available in the Angular version 8 with Angular Ivy opt-in.

    Pipeine angular ivy

    Ivy is a complete rewrite of Angular’s rendering engine. In fact, it is the fourth rewrite of the engine and the third since Angular 2. But unlike rewrites two and three, Ivy promises huge improvements to your application. With Ivy, you can compile components more independently of each other. This improves development times since recompiling an application will only involve compiling the components that changed. 

    Concepts of IVY

    Locality and tree shaking are two key aspects that Ivy always considers. They both are able to make Ivy capable of what it can do. The process of independent compilation of every component with its information. The partial changes are compiled in the process that makes the process faster by not changing all the project files. 

    Tree Shaking

    Tree shaking is a term that means removing unused code during the bundling process. This can be done by using tools like Rollup and Uglify. During the build process, tree shaking tools use static analysis and eliminate the unused and unreferenced code. However, tree shaking tools have limitations when the conditional code exists as static analysis depends on references. For example, an unused code path within an “IF” statement cannot be identified by a static analyzer and that code still resides in the bundle even if it is not used during runtime. Due to the above-mentioned limitations, the current rendering pipeline is modified to optimize the bundle size.

    Locality

    The locality is the process of compiling each component independently with its own local information that rebuilds faster by compiling partial changes and not the entire project files. This increases the speed of your build process. In the current angular code, each component has its parent information, which leads to compilation dependencies, whereas in Ivy, each component is independent. To compile a component in Ivy, Angular only needs information about the component itself, except for the name and package name of its declarable dependencies. Most notably, Ivy doesn’t need metadata of any declarable dependencies to compile a component. The principle of locality means that in general we will see faster build times.

    The Ivy Compilation Model`

    In the Ivy model, Angular decorators (@Injectable, etc) are compiled to static properties on the classes (ngInjectableDef). This process takes place without a complete analysis of code, and in most cases with a decorator only. Here, the only exception is @Component, which requires knowledge of the meta-data from the @NgModule which declares the component in order to properly generate the ngComponentDef. The selectors which are applicable during the compilation of a component template are determined by the module that declares that component.

    The information needed by Reference Inversion and type-checking is included in the type declaration of the ngComponentDef in the .d.ts. Here, Reference Inversion is the process of determining the list of the components, directives, and pipes on which the decorator(which is getting compiled ) depends, allowing the module to be ignored altogether. 

    IVY in Angular 8

    Angular Ivy is an enabler for features to come. This article discusses the benefits that IVY provides as a renderer. However, the best features are to come in future versions of Angular. Which of the possible features that will be delivered in Angular versions 10 and 11, that is still to be decided. But first, let's have a look at the benefits that come with Angular 8.

    contact us

    Features of IVY in Angular 8

    Lazy-loaded components

    entryComponents declarations are deprecated as they are no longer needed. Any Ivy component can be lazy-loaded and dynamically rendered. This means that we can now lazy load and render a component without routing or Angular modules. However, in practice, we have to use component render modules or feature render modules to link a component’s template to its declarable dependencies. Libraries that are only used by a lazy-loaded component are even bundled in lazy-loaded chunks.

    Improvements to Differential Loading

    ivy differential loading saving

    At the time when differential loading was introduced in Angular version 8, the build process was run once for the ES5 bundle and once for the ES2015+ bundle. In Angular version 9, an ES2015+ bundle is an output first. That bundle is then transpired to a separate ES5 bundle. This way, we don’t have to go through a full build process twice.

    AOT Compilation Everywhere

    AOT compliaton

    AOT is enabled by default in builds, the development server and even in tests. Previously, AOT compilation was significantly slower than JIT compilation so JIT was used for development and testing. With the build and rebuild time improvements in Ivy, AOT-compilation now has a great developer experience. When we used JIT compilation in some phases of our process and only AOT compilation in the final build, errors were detected only when doing production builds or worse, at runtime.

    Bundle Sizes

    Ivy can enable smaller bundles because it uses the Ivy Instruction Set which is a set of tree-shakable runtime rendering instructions. Our bundles will only include the rendering instructions we use in our projects. This is great for use cases such as micro frontends, Angular Elements and web apps where Angular is not controlling the entire document. However, the difference in our bundle sizes between View Engine and Ivy will vary based on the size of our application and the 3rd party libraries we use. In general:

    • Small and simple applications will see a considerable bundle size decrease.
    • Complex applications will see an increase in the main bundle, but a decrease in lazy loaded bundle sizes.

    This means a considerable combined bundle size decrease for big applications but could mean an overall increase in bundle size for medium-sized applications. In both cases, the main bundle’s size will probably increase which is bad for the initial page load time.

    Globalization

    Locales (number formatting, date formatting, and other regional settings) can be dynamically loaded at runtime instead of having to be registered at compile time.

    // main.ts 
    import '@angular/localize/init';

    import { loadTranslations } from '@angular/localize';

    loadTranslations({
    '8374172394781134519': 'Hello, {$username}! Welcome to {$appName}.',
    }
    );

    Multiple languages from a single application bundle

    To change language, we have to restart the application, but we don’t have to serve a different application bundle.This means that we can?, ?with some setup, ?support multiple languages with a single application bundle on a single hostname.

    Read More: Angular 10 New Features and Ivy Compiler 

    Compile-time inlining

    A localised application will only be compiled once in Angular 8. Instead of multiple builds to produce a bundle per language, a bundle per language is produced by replacing $localize placeholders with translated texts. We now need to add the package @angular/localize to support localisation (multiple languages). The good news is that we no longer have to include Angular’s localisation code in our bundles if we only have a single language. If we don’t use localised templates, the i18n* Ivy instructions are tree-shaked from the bundle. 

    Additional provider scopes

    We have always had an Angular module scope for providers. Angular version 6 introduced the 'root' provider scope and tree-shakable providers both for root and Angular module scope providers. Angular version 9 introduces the 'platform' and 'any' provider scopes. Platform-scoped providers can be shared between multiple Angular applications in the same document. The 'any' provider scope will share a provider per module injector. For example one service instance for the eagerly loaded main bundle and one service instance for each lazy-loaded Angular module.

    Improved developer experience

    Ivy enables the Angular Language Service to support additional checks while developing. This is a big improvement to the developer experience.

    File path checks- The Angular Language Service continuously verifies component stylesheet and template paths.

    Template type checks- Templates are type-checked, according to the template type checking mode as described in the “Strict mode” section. Member names and types are verified, even in embedded views. What previously resulted in runtime errors are now detected while developing and building. Curiously enough, this doesn’t add the same options as if we would simply set "strict": true in the compilerOptions object. Let’s compare the Angular workspace strict option to the TypeScript compiler strict option.

    Strict template type checking- We have had the option to enable template type checking since Angular version 5 by setting "fullTemplateTypeCheck": true in the angularCompilerOptions object. Ivy introduces strict template type checking as seen in Listing 5. When this new Angular compiler option is set, the value offullTemplateTypeCheck is ignored.

    {
    "//": "tsconfig.json",
    "angularCompilerOptions": {
    "strictTemplates": true
    }
    }

    The strict template type checking verifies the types of property bindings and respects the strictNullChecks option. It also checks the types of template references to directives and components, including generic types. Template context variables’ types are also checked which is great for NgFor loops. The $event type is checked for event bindings and animations. Even the type of native DOM elements is verified with strict template type checking. 

    Improved styling experience

    Styling in Angular Ivy has been reworked. Combining static HTML classes with NgStyle and NgClass directives is now fully supported and easier to reason about. As part of the Ivy styling rewrite, binding CSS Custom Properties is now supported.CSS Custom Properties have scope, so this CSS property would be scoped to the component’s DOM.

    Enable Angular Ivy

    Ivy can be enabled in an existing project with the latest Angular version but also directly scaffold a project with Ivy.

    Enable Ivy in an existing project

    Having an existing Angular (8.1.x) project run:

    $ ng update @angular/cli@next @angular/core@next 

    both the Angular core and the CLI will be updated at the latest release candidate. One interesting thing to notice is the "aot": true in the angular.json workspace configuration file:

    AOT compilation with Ivy is faster and should be used by default.

    Then add the angular compiler options in the tsconfig.app.json:

    {
    "compilerOptions": { ... },
    "angularCompilerOptions": {
    "enableIvy": true
    }
    }
    New project with Ivy
    To start a new project with Ivy run:
    $ new my-app --enable-ivy

    Disable Ivy

    To disable Ivy:

    • in angular.json set "aot": false;
    • in tsconfig.app.json remove the angularCompilerOptions option or set "enableIvy": false.

    IVY in Angular 9

    Even though Angular 9 has some extraordinary updates like improved ng update, support for TypeScript, and inline rendering support for YouTube and Google Maps, the default Ivy compiler has grabbed the attention of developers worldwide with its unbeatable features. The Angular Ivy version 9 release gives us improvements for bundling, testing, the developer experience, tooling, debugging, and type checking. Quite a good collection of features. Let's have a look at them. 

    Ivy enabled by default

    In previous versions of Angular, we had to opt-in to Ivy. In version 9, we instead have to opt-out of Ivy if we want to fall back to View Engine. This is possible in both angular versions 9 and 10 to ensure a smoother transition from View Engine to Ivy. Libraries can be AOT-compiled directly to Ivy instructions and metadata, but this is not recommended. 

    The Angular team has a View Engine-to-Ivy migration plan which recommends only publishing AOT-compiled View Engine-compatible libraries for Angular version 9. The Angular compatibility compiler will upgrade View Engine-compatible libraries to Ivy when installed in an Angular Ivy application project.

    IVY rendering engine

    This new compiler and rendering pipeline became the default with Angular 9 by replacing ViewEngine. This more efficient renderer ensures less code for the same action that required a lengthy code earlier. The main benefit of the Ivy compiler is you can make small-sized bundles and make incremental compilation simple. 

    The focus of this complete rewriting of the compiler includes faster testing, smaller bundle sizes, better debugging, better type checking, better build errors, internalization, enhancing CSS class & styling and improved build times with AOT bundles. Let’s dig deep into what you can do for your business by using Angular 9 with Ivy.

    Faster mobile apps

    Half of the website traffic is generated only through mobile devices. A significant percentage of web page access through mobiles is suffering from slow internet connections. It is possible to redesign the applications to reduce its downloadable size and improve the mobile user experience, but it is difficult, expensive, and can cause unforeseen risks to the apps. 

    Ivy initiates a step to speed up app startup by reducing the factory sizes. As such, Angular applications built with Angular 9 will be more efficient and faster. 

    Reduced bundle size

    With the Ivy instruction set, Angular 9 detects the unused code called tree-shaking rendering instruction and reduces bundle size. This offers substantial benefits for use cases like Angular elements, web apps and micro frontends where Angular framework is not governing the entire elements. This makes a considerable bundle size decrease for small & simple apps and a drop in lazy loaded bundle size for complex apps.

    Additionally, code splitting helps to optimize the bundles further. This process splits the code into smaller chunks as well as lazy loads using angular routes. Splitting of code into possible routes makes it easy to load features that are used in those routes.

    AOT compilation

    Earlier, AOT compilation was slower than JIT compilation; it was used only in the final build, not in development and testing. As such, errors were identified only during production or at runtime. The build and rebuild time enhancement in Ivy, empowers AOT to offer an improved developer experience. In Angular 9, AOT compilation is enabled by default in the development server and tests. The angular team measured the performance of the compiler in terms of overhead with AOT builds and found it is noticeably faster. For their documentation app, the overhead has declined from 0.8x to 0.5X, which is nearly 40% improvement in performance.

    Internationalization

    Internationalization (i18n) is a core feature in Angular, which acts as a key factor when developing applications worldwide. It is the process of building apps in a way that can be localized for cultures and languages easily. In Angular 9.0, the Ivy makes this process faster by introducing a new package known as

     @angular/localize

    This new feature makes internationalization 10 times faster than in previous versions. Default Currencies It is a bit burdensome when you have to mention the currency every time, but your app uses only one currency type, EUR, for example. You can configure the Default currency in Angular 9. The currency pipeline in 9.0 comes with the option to select the currency of your preference.

    Enhanced styling experience

    Angular Ivy comes with reworked styling features. The rewrite enables the support of CSS custom properties binding. In earlier versions, if an app includes competing definitions for a CSS style, those CSS properties would replace each other. But in Angular Ivy with CSS custom properties support, the styles can be merged effectively. 

    Improved build process

    The Ivy compiler enables faster compilation of Angular applications. Google states that they saw ~40% improvement with their angular.io documentation app. Besides the obvious benefit of faster compilation times, the new process also allowed Angular to start using AOT (or Ahead of Time) compilation during the development process (when using ng serve).

    Until recently, AOT compilation was limited to production builds due to the long compilation time required, which resulted in some edge cases where builds would pass in development, but fail in production

    Faster testing

    Angular 9.0 includes several surprising improvements to testing. New concepts are added, long-standing performance problems are resolved, and types are improved. The implementation of TestBed is revamped to make Ivy more efficient. Previously, irrespective of any changes done to the components, TestBed was used to recompiling the entire component while running each test.

    However, in Angular Ivy, it recompiles components only when there has been any manual override, which avoids recompilation in a majority of tests. It is expected that users can experience a 40 to 50 % increase in speed in their app testing. 

    Better debugging

    Ivy discloses new additional capabilities to Debug mode that allows you to manually update stage, trigger change detection, call method and access instances of components. Angular Ivy also made improvements in the stack trace. When code encounters an error, it offers accurate links to the affected lines of code.

    Opting out of Ivy in version 9

    In version 9, Ivy is the default. For compatibility with current workflows during the update process, you can choose to opt-out of Ivy and continue using the previous compiler, View Engine.

    To opt-out of Ivy, change the angularCompilerOptions in your project's TypeScript configuration, most commonly located at tsconfig.app.json at the root of the workspace.

    The value of the enable Ivy flag is set to true by default, as of version 9.

    The following example shows how to set the enable Ivy option to false in order to opt-out of Ivy.

    {
    "extends": "./tsconfig.json",
    "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
    },
    "files": [
    "src/main.ts",
    "src/polyfills.ts"
    ],
    "include": [
    "src/**/*.d.ts"
    ],
    "angularCompilerOptions": {
    "enableIvy": false
    }
    }

    If you disable Ivy, you might also want to reconsider whether to make the AOT compilation the default for your application development.

    To revert the compiler default, set the build option aot: false in the angular.json configuration file. 

    Conclusion:

    Angular ivy performance

    The future of Angular with IVY looks exciting with some of the incredible features that Angular comes up with every new version. In Angular 10 and Angular 11, Ivy completely takes over the compiler (Angular Ivy compatibility compiler) and provides a stronger core structure than ever.  Ivy is a very important stepping stone in Angular history. It changes how the framework internally works, without changing Angular web app development and it also sets the ground for Angular Elements to become much more popular in our Angular applications.

    Read More: Angular 11 Features - Everything About Latest Features & Updates

    24

    Related articles

    This website uses cookies to analyze website traffic and optimize your website experience. By continuing, you agree to our use of cookies as described in our Privacy Policy.