What is the difference between Angular AOT and JIT compiler

前端 未结 3 1883
一生所求
一生所求 2020-12-14 03:57

I am diving into angular 4 and I am trying to understand the compilation. I\'ve read that AOT and JIT both compile TypeScript to JavaScript whether that is server side or on

3条回答
  •  粉色の甜心
    2020-12-14 04:34

    I've read that AOT and JIT both compile TypeScript to JavaScript whether that is server side or on the client side.

    No, that is not what AOT and JIT compilers do. TypeScript is transpiled into JavaScript using typescript compiler.

    Angular compiler

    There are two compilers that do the hard work of compilation and code generation:

    • view compiler
    • provider compiler

    The view compiler compiles component templates and generates view factories. It parses expressions and html elements inside the template and goes through many of the standard compiler phases:

    parse-tree (lexer) -> abstract-syntax-tree (parser) -> intermediate-code-tree -> output
    

    The provider compiler compiles module providers and generates module factories.

    JIT vs AOT

    These two compilers are used in both JIT and AOT compilation. JIT and AOT compilations differ in how they get the metadata associated with the component or module:

    // the view compiler needs this data
    
    @Component({
       providers: ...
       template: ...
    })
    
    // the provider compiler needs this data
    
    @NgModule({
       providers: ...
    });
    

    JIT compiler uses runtime to get the data. The decorator functions @Component and @NgModule are executed and they attach metadata to the component or module class that is later read by Angular compilers using reflective capabiliteis (Reflect library).

    AOT compiler uses static code analysis provided by typescript compiler to extract metadata and doesn't rely on code evaluation. Hence it's a bit limited when compared to JIT compiler since it can't evaluate in-explicit code - for example it requires exporting a function:

    // this module scoped function
    
    function declarations() {
      return [
        SomeComponent
      ]
    }
    
    // should be exported
    
    export function declarations() {
      return [
        SomeComponent
      ];
    }
    @NgModule({
      declarations: declarations(),
    })
    export class SomeModule {}
    

    Again, both JIT and AOT compilers are mostly wrappers to extract metadata associated with a component or module and they both use the underlying view and provider compiler to generate factories.

    If I am compiling it when I build it with Webpack and grunt and deploying that minified javascript how does AOT and JIT even come into the picture?

    Angular provides webpack plugin that performs transpilation from typescript during build. This plugin can also AOT compile your project so that you don't include JIT compiler into the bundle and don't perform compilation on the client.

提交回复
热议问题