Skip to content

RFC: Exploration of use-cases for Angular JIT compilation mode #43133

Closed

Description

@IgorMinar

Note: 📺 Check out the video recording of a community discussion about this RFC @ angularnation.net

Summary

The Angular team would like to understand the remaining use-cases for Angular's JIT compilation mode, and discover any gaps that prevent adoption of the AOT compilation mode for these use-cases.

We'd like you, the community, to share with us how and why you still use JIT mode, and what prevents you from using AOT.

Background information

When Angular launched as v2.0 back in 2016, the template compiler supported two distinct compilation modes: JIT (just in time) and AOT (ahead of time) compilation.

While initially JIT was readily available and the primary mode for both development and production build workflows, our intention has always been to primarily focus on AOT mode which was harder to implement, but offered more opportunities to improve the development experience (e.g. type checking, autocompletion, automated refactoring, and faster development server and unit testing incremental iteration cycle), as well as user experience (faster and smaller apps, thanks to significantly better runtime and payload size optimizations).

Over the last many releases we overhauled the AOT compiler and kept on improving it. As of Angular v9 the AOT compilation mode is the default for all development and production workflows for all CLI application and library workflows (it's been the default at Google for much longer than that). There are only a few remaining cases where JIT compilation is still used:

  • unit testing workflows which run either in mixed JIT+AOT mode, or JIT-only mode
  • use-cases relying on dynamically generating templates and views at runtime
  • the legacy and long-deprecated dynamic upgrade layer within @angular/upgrade
  • customized build pipelines of large monolithic projects that use JIT to speed up incremental builds for interactive workflows

The use of the JIT compiler for these use-cases suffers from a lack of type checking, as well as performance and security issues that are a side-effect of compiling code at runtime in the browser (and in the JavaScript context shared with the production application).

The security implications are serious enough that our Information Security Engineering team at Google has early-on disallowed the use of Angular's JIT compiler in production environments at Google.

As of v13, the legacy View Engine compilation pipeline will no longer be part of Angular's stack (more info and also here), which significantly simplifies Angular, especially for library authors, which have had to ensure compatibility of their libraries with both View Engine and Ivy during the transition.

It is our goal to keep making Angular simpler and streamline internal complexity that affects Angular application developers and library authors in direct and indirect ways, and as part of this effort we'd like to evaluate if keeping JIT compilation mode around is still providing Angular developers with value that justifies the increase in complexity, security risks, and maintenance cost for everyone, including Angular application developers, library developers, as well as the Angular team.

There are many benefits to standardizing on AOT compilation mode, the main ones include:

  • consistency and predictability — JIT and AOT modes behave identically once all the templates & metadata are collected, and all the JavaScript references (module imports, class references, etc) are resolved. However, the collection of templates & metadata, and resolution of JavaScript symbols is significantly different between AOT and JIT, and requires special considerations in the application and library code (inconsistent behavior of what can and cannot be declared with Angular's decorators), in the library packaging format (the npm packages must support both JIT and AOT compilation), and also in the Angular compiler and runtime, which needs to accomodate the needs and quirks of both JIT and AOT.

  • fewer runtime performance and security pitfalls, and fewer confusing APIs for developers — for example the @angular/platform-browser-dynamic package and the Compiler APIs could be removed.

  • addition of view composition APIs to support commonly requested use-cases that are currently handled via JIT compilation — for example dynamic view composition (e.g. new core APIs for dynamically assembling and composing views out of directives, and components at runtime to support data-driven form, and other UIs).

  • focus on further build time improvements for AOT — for example by out-of-band type-checking for TypeScript and Template compilation, and transition to parallelizable localized compilation.

Community feedback

We'd like the community to share with us how and why you still use JIT mode, and what prevents you from using AOT.

We are specifically interested to know if there are use-cases that we are not familiar with (not listed in this RFC)?

Additionally, we'd also like to hear if you face organizational or technical restrictions that require you to use the JIT compilation mode?

The information provided by the community will help us understand what gaps we need to fill, and if it is feasible to deprecate and remove the JIT mode some time in the future once all the significant gaps are filled.

This RFC will close on Sep 8, 2021. Thank you for participating!

Activity

  1. added
    needs: discussion
    area: compiler
    area: core
    on Aug 12, 2021
  2. modified the milestone: Backlog on Aug 12, 2021
  3. eugene-stativka commented on Aug 13, 2021

    @eugene-stativka

    I’ve never seen any use case for JIT in any app I worked on over the last 5 years. Always —aot.

  4. jnizet commented on Aug 13, 2021

    @jnizet
    Contributor

    TBH, I don't know for sure if that involves JIT mode or not, but I suspect it might. What I'm sure is that it's a common practice, so you've probably thought about it already. But many of my unit tests consist in having test host components that are only ever declared in the testing module:

    @Component({
      template: '<component-under-test ...></component-under-test>'
    })
    class TestComponent {
      ...
    }
    
    describe('some test', () => {
      beforeEach(() => {
        configureTestingModule({
          declarations: [ComponentUnderTest, TestComponent]
        }
      });
    
      ...
    }

    Some times, the template of the test component is dynamic, i.e. it's overridden in each of the tests to test various combinations of inputs and outputs. That's why I guess it uses the JIT. If such a feature wasn't supported anymore, it would imply a huge amount of re-design and rewrite of the tests.

  5. SanderElias commented on Aug 13, 2021

    @SanderElias
    Contributor

    I would say, get rid of it as soon as the view composition APIs is in a stable state, as that would fulfill all of the use-cases JIT is now used for.
    (assuming proper replacements using view composition are in place for testing)

    When this, and the related RFC's do speed things up enough, the custom builds using JIT will become unneeded anyway

  6. IgorMinar commented on Aug 13, 2021

    @IgorMinar
    ContributorAuthor

    @jnizet great point! Thank you. You are right that the testing components today rely on JIT. Usually not because they are dynamic but because you need the flexibility to declare them inline, usually within functions of a test file as your example shows.

    With the right compiler and API modifications we should be able to support this with AOT (thanks to Ivy). This change could be rolled out with an automated migration so nobody has to rewrite their tests.

    But as you bring up, this flexibility of testing components means that you could dynamically create a template or modify the component metadata (e.g. use string concat and interpolation to create a unique template for a bunch of components created within a loop that wraps an it or describe.

    This is not the most common pattern but I'd be shocked if some codebases didn't rely on it. I currently don't have a solution for this one. Maybe the composition api could be it, but automated migration from unconstrained TS/JS code that generates a component to a component built using the composition API would be tricky and not 100% reliable.

    I do appreciate bringing this up though. This is exactly the kind of feedback we are looking for.

  7. ahnpnl commented on Aug 13, 2021

    @ahnpnl
    Contributor

    We use JIT mainly for unit testing only, especially with Jest. Currently, we follow slightly similar setup how Angular CLI did is that:

    If removing platform-browser-dynamic, I believe CLI team also needs to change the way to init test environment. It isn’t really a problem for us to migrate if there is a clear way to replace that way of initialization.

    Regarding to code emitting, IIRC AOT compiler uses some extra AST transformers besides the above 2 which I think will be the most work for us to replicate the same behavior for Jest.

    We would love to use AOT compiler for Jest but will need to spend some time first to experiment. Ofc using everything from Angular is the best way. My concern only is how open the AOT compiler APIs will be so that we can reuse them.

  8. kroeder commented on Aug 13, 2021

    @kroeder
    Contributor

    @storybook/angular relies on JIT right now.

    Storybook users write story files like this one
    https://github.com/storybookjs/storybook/blob/next/examples/angular-cli/src/stories/welcome-angular.stories.ts

    export default {
      title: 'Welcome/ To Angular',
    } as Meta;
    
    export const toAngular: Story = () => ({
      component: AppComponent,
      props: {
        showApp: linkTo('Button'),
      },
    });

    A story contains metadata to generate the actual NgModule and render the component or template during runtime. This information is not available during compile-time and therefore is not compatible with AoT, right? Actually, the story is. But not the generated NgModule and Component.

    Here's one example of what Storybook does with the provided metadata information of a story
    https://github.com/storybookjs/storybook/blob/next/app/angular/src/client/preview/angular-beta/StorybookModule.ts#L30

    export const createStorybookModule = (ngModule: NgModule): Type<unknown> => {
      @NgModule(ngModule)
      class StorybookModule {}
      return StorybookModule;
    };

    I talked about this with Alan, Minko and Alex during the Storybook Ivy integration and I remember one of them said: "Maybe, it is possible to partly make Storybook AoT compatible as a second step" but we didn't talk about this any further.

  9. johncrim commented on Aug 13, 2021

    @johncrim

    We care about Jest tests (for faster dev cycles) and a home-grown app for demoing components using templates that are compiled at runtime. Most developers will probably use Storybook, but we use something similar to this to host angular examples within an angular app:

    https://github.com/johncrim/angular-dynamic-styleguide

    Here's the part that compiles templates:

    https://github.com/johncrim/angular-dynamic-styleguide/blob/master/src/app/examples/template-examples.service.ts

    The general problem description is: "How do we render angular component code alongside working examples of that code?" I'm sure that if the problem is solved well for aio and storybook we can use the same approach.

    We'd be happy to migrate to a new way to accomplish the same thing once it's available.

  10. IgorMinar commented on Aug 13, 2021

    @IgorMinar
    ContributorAuthor

    @ahnpnl, @kroeder, and @johncrim this is exactly the kind of feedback we are looking for! Thank you for sharing the links and examples.

    My first impression is that Jest, Storybook, and example use case would be fully supported using a combination of the proposed view composition APIs (primarily for the demo use cases) and whatever solution we implement to AOT compile testing components within unit tests (for jest and storybook).

    Do you see any obvious holes in these solutions? (I apologies for the lack of clarity around the solution for unit tests, I'll see if I can write something up in the next few days to make it less ambiguous)

  11. mattlewis92 commented on Aug 13, 2021

    @mattlewis92
    Contributor

    We are still using JiT mode for local development for our large app (~1300 components), as AoT is still noticeably slower for incremental rebuilds. v12 and webpack's in memory caching helped a lot to make this better as previously a single line change in a component would take more than a minute to rebuild, now after a few rebuilds it goes down to about 14s, although it's still double the speed of JiT mode on the same file (apx 7s). The first few changes to the file are always a lot slower as well (1st: ~79s, 2nd: ~28s, 3rd: ~14s). We'd be happy to arrange access to the repo for an angular team member to do some profiling to see if it's possible to get it down to match the speed of JiT mode 😄

  12. 32 remaining items

  13. LayZeeDK commented on Sep 2, 2021

    @LayZeeDK
    Contributor

    Spectactular's pipe testing API allows the user to decide the template of the (internal) host component for integration testing an Angular pipe. How would we solve this using the imperative view composition API or otherwise, without JIT in tests?

    import {
      createPipeHarness,
      SpectacularPipeHarness,
    } from '@ngworker/spectacular';
    
    import { PowPipe } from './pow.pipe';
    
    describe(PowPipe.name, () => {
      beforeEach(() => {
        harness = createPipeHarness({
          pipe: PowPipe,
          // template: '{{ value | pow }}' // 👈 Default host component template
          value: 2,
        });
      });
    
      let harness: SpectacularPipeHarness;
      
      it('raises the base to the specified power', () => {
        harness.value = 5;
        harness.template = '{{ value | pow:3 }}'; // 👈 Resets the Angular testing module and overrides the host component template
    
        expect(harness.text).toBe('125');
      });
    });
  14. Johnnyrook777 commented on Sep 3, 2021

    @Johnnyrook777

    I am using the JIT compiler to build up text document fragments. We allow our staff to define templates (HTML) and bind them to a model via JIT and compileModuleAndAllComponentsAsync.
    We use a few things to help render text/dom on the screen, namely *ngIf, *ngFor, {{ }}, {{ x | customPipe }}

    Its really powerful as we can just point them to some angular basics, build some custom pipes for the tricky stuff, and let them at it.

  15. IgorMinar commented on Sep 3, 2021

    @IgorMinar
    ContributorAuthor

    @lacolaco I agree with you that for testing use cases, using strings as inputs is important. I think we can support this by translating/transpiling strings with templates being tested to the view composition API calls.

    From the DX perspective it works in the same way, but under the hood it won't require JIT compiler, which would be a huge win for all of us.

  16. IgorMinar commented on Sep 3, 2021

    @IgorMinar
    ContributorAuthor

    @matthewjh could you please share some examples that capture various usage patterns? I'd love to know more to determine if these patterns are already captured in the use-cases we discussed above or if they are unique. thanks

  17. IgorMinar commented on Sep 3, 2021

    @IgorMinar
    ContributorAuthor

    I really appreciate all the feedback we've received from all of you. This RFC was supposed to close this week, but I like the conversation and I'd like to finish some of the unresolved questions around testing use-cases, and CMS-like use-cases.

    From what I've seen in the feedback so far, I think we can have a solid story for all the concerns raised even without JIT compiler, as long as we implement some of the proposed features to fill in the current gaps in AOT capabilities and DX.

    If you have more details you'd like to share with us, please do so by next Wednesday, September 8. Thank you! 🙇🏻 🖖🏻

  18. LayZeeDK commented on Sep 4, 2021

    @LayZeeDK
    Contributor

    @lacolaco I agree with you that for testing use cases, using strings as inputs is important. I think we can support this by translating/transpiling strings with templates being tested to the view composition API calls.

    From the DX perspective it works in the same way, but under the hood it won't require JIT compiler, which would be a huge win for all of us.

    Yes, this also ties into the Spectacular use case. Having that string template to imperative view composition feature to optionally add would be great. API bundle size doesn't matter as much for testing so it's the perfect companion to keep supporting the rich ecosystem of Angular testing libraries. Maybe it could even be a choice for bundling at runtime for dynamic scripting-like use cases if bundle size is less of a concern, similar to bundling the JIT compiler today for dynamic runtime composition.

  19. matthewjh commented on Sep 8, 2021

    @matthewjh
    Contributor

    @IgorMinar

    @matthewjh could you please share some examples that capture various usage patterns? I'd love to know more to determine if these patterns are already captured in the use-cases we discussed above or if they are unique. thanks

    Let's say we are testing a component A that utilises another component or directive B from our codebase (I'll just say "directive" from here onwards). This directive may reside in the app itself or in a library in our monorepo. In the test for A, we will configure the testing module with declarations = [mockDirective(A)]. mockDirective will read the ng metadata for A via ReflectionCapability (semi-protected, I know), and create a new directive class that has the same selector as A, iterating through A's inputs and outputs, recreating them on the mock ADirective. Outputs are initialised with new EventEmitters. The idea is to eliminate boilerplate code in tests, as well as to provide batteries-included mocks, without pulling in implementations of collaborators into unit tests.

    So in a nutshell, we would need to be able to:

    1. Read the ng metadata for ng-things
    2. Dynamically create new ng-things with certain pieces of ng metadata, including property metadata like inputs/outputs
    3. Be able to use these dynamically created ng-things with parity to static ng-things
  20. meriturva commented on Sep 16, 2021

    @meriturva

    Sorry @IgorMinar, I'm late on the discussion.

    As already described to @mgechev we have a quite big application where we compose on runtime routing and loading dynamically modules using systemjs (quite old application), of course, based on JIT Compiler.

    Just a short question related to Ivy and AOT:

    will it be possible to compile single modules (angular library) with ivy compilationMode = full
    then use modules compiled as a dynamic import during runtime routing configuration (maybe with a custom webpack configuration)?

    Using that approach we will be free to remove jit compiler on our project.

  21. flash-me commented on Sep 16, 2021

    @flash-me
    Contributor

    @meriturva This is already possible.

    UPDATE:
    Just in case someone is asking
    cheers
    flash ⚡

  22. RobinVdBroeck commented on Sep 23, 2021

    @RobinVdBroeck

    This RFC will close on Sep 8, 2021. Thank you for participating!

    When can we expect the conclusion of the Angular Team? Any timeline?

  23. unpinned this issue on Oct 5, 2021
  24. IgorMinar commented on Oct 12, 2021

    @IgorMinar
    ContributorAuthor

    Hey everyone, thanks for participating in this RFC. I'm finally wrapping up this one now that the RFC for standalone components, directives, and pipes is out. Several of the sub-rfc of this RFC referred to the "standalone" design, so I'm glad that all of the information is out there and up for discussion.

    The key takeaways from this RFC for me are:

    1. nobody strongly objects to removal of JIT mode as long as all of the existing use-cases are covered

    2. the biggest gaps discovered via this RFC are:

      1. Jest and Storybook integration rely on JIT, so we'd need to work with these teams to get them off. This seems doable.

      2. AOT build speed and edit/refresh latency is a concern for several people with large applications. I think we can tackle this via build latency improvements that are already being planned.

      3. Dynamic view creation is a big deal for several applications that either

        • lazy load templates and compile them on the fly ("federated" apps, or apps with plugins), or
        • enable users to create templates (CMSes, drag&drop UI builders)
        • or unit tests where it's desirable to express the testing component using the Angular template syntax

        All of these use cases can be handled via Imperative View & Template Composition APIs and ability to AOT compile testing components embedded in unit tests, but as surfaced via this RFC, it would be great to also consider providing a simplified declarative API for view creation inspired by tshtml.

    Overall, my take on this RFC is that JIT is not going to disappear any time soon, but if we fill in all the gaps, it could disappear in the future. Thank you all for participating in the discussion.

  25. angular-automatic-lock-bot commented on Nov 12, 2021

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  26. locked and limited conversation to collaborators on Nov 12, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    action: discussarea: compilerarea: coreneeds: discussion

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions