Search code examples
angularaotangular-compilerangular-dynamic-components

Angular: How to import JitCompilerFactory?


If I use AOT compilation dynamic compilation will not possible. So I need to load the compiler to a browser. So how do I load it? If I use

import { JitCompilerFactory } from '@angular/compiler';

However, after importing the JitCompilerFactory I am getting the following error:

"export 'JitCompilerFactory' was not found in 'angular/compiler

So am I right that now I need to import it from 'angular/platform-browser-dynamic' for dynamic compilation?


Solution

  • You need to import JitCompilerFactory into your app.module.ts like this:

    import {Compiler, COMPILER_OPTIONS, CompilerFactory} from '@angular/core';
    import {JitCompilerFactory} from '@angular/platform-browser-dynamic';
    export function createCompiler(compilerFactory: CompilerFactory) {
      return compilerFactory.createCompiler();
    }
    
    
    
    @NgModule({
      declarations: [
        AppComponent,
      ],
      imports: [
        BrowserModule
      ],
      providers: [
        {provide: COMPILER_OPTIONS, useValue: {}, multi: true},
        {provide: CompilerFactory, useClass: JitCompilerFactory, deps: [COMPILER_OPTIONS]},
        {provide: Compiler, useFactory: createCompiler, deps: [CompilerFactory]}
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    Here I created a fully working StackBlitz Demo with a Dynamic Component if you want to play around with it on there.