As an entry module for Angular applications, it’s important to know! @angular/ platform-browser-Dynamic: @angular/ platform-browser-Dynamic: @angular/platform-browser-dynamic Hope watching this article is useful to you!

Main. ts looks like this, and I’m going to unlock platformBrowserDynamic!

import { platformBrowserDynamic } from 'iwe7/platform-browser-dynamic';
platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch(err => console.log(err));
Copy the code

PlatformBrowserDynamic source

exportConst platformBrowserDynamic = createPlatformFactory(platformCoreDynamic, // name'browserDynamic'// Inject the service to use INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS);Copy the code

PlatformCoreDynamic source

export const platformCoreDynamic = createPlatformFactory(
  // @angular/core
  platformCore,
  / / name
  'coreDynamic'[// Configure the build project
    { provide: COMPILER_OPTIONS, useValue: {}, multi: true },
    {
      // Customize CompilerFactory classes to replace or implement CompilerFactory, the core should be here!!
      provide: CompilerFactory,
      useClass: JitCompilerFactory,
      deps: [COMPILER_OPTIONS]
    }
  ]
);
Copy the code

By looking at the source code, we found the JitCompilerFactory, the core of the JitCompilerFactory class

JitCompilerFactory source code, the core distribution is createCompiler

export class JitCompilerFactory implements CompilerFactory {
  private _defaultOptions: CompilerOptions[];

  /* @internal */
  constructor(defaultOptions: CompilerOptions[]) {
    const compilerOptions: CompilerOptions = {
      useJit: true, / / configuration to defaultEncapsulation: ViewEncapsulation. Emulated, missingTranslation: MissingTranslationStrategy. Warning}; this._defaultOptions = [compilerOptions, ...defaultOptions]; } createCompiler(options: CompilerOptions[] = []): Compiler { const opts = _mergeOptions(this._defaultOptions.concat(options)); Const Injector = Injector. Create ([// Create Compiler's core COMPILER_PROVIDERS,]);returninjector.get(Compiler); }}Copy the code

Find the core key COMPILER_PROVIDERS and find the core of @angular/platform-browser-dynamic

exportConst COMPILER_PROVIDERS = <StaticProvider[]>[provide: CompileReflector, useValue: New JitReflector()}, // ResourceLoader- ResourceLoader {provide: ResourceLoader, useValue: _NO_RESOURCE_LOADER}, // Jit summary resolver {provide: JitSummaryResolver, deps: []}, // Summary resolver {provide: SummaryResolver, useExisting: JitSummaryResolver}, {provide: Console, deps: []}, // Parser {provide: Lexer, deps: []}, // Parser {provide: Parser, deps: [Lexer]}, {// Basic HTML parsers provide: baseHtmlParser, useClass: HtmlParser, deps: []}, {/ / international HTML parser dojo.provide: I18NHtmlParser, useFactory: (parser: HtmlParser, translations: string | null, the format: string, config: CompilerConfig, console: Console ) => { translations = translations ||' '; const missingTranslation = translations ? config.missingTranslation! : MissingTranslationStrategy.Ignore; // new internationalized HTML parserreturnnew I18NHtmlParser( parser, translations, format, missingTranslation, console ); }, deps: [ baseHtmlParser, [new Optional(), new Inject(TRANSLATIONS)], [new Optional(), new Inject(TRANSLATIONS_FORMAT)], [CompilerConfig], [Console]]}, {provide: HtmlParser, useExisting: I18NHtmlParser}, {// Template parser provide: TemplateParser, deps: [CompilerConfig, CompileReflector, Parser, ElementSchemaRegistry, I18NHtmlParser, Console]}, {provide: DirectiveNormalizer, deps: [ResourceLoader, UrlResolver, HtmlParser, CompilerConfig]}, {// Metadata parsers provide: CompileMetadataResolver, deps: [ CompilerConfig, HtmlParser, NgModuleResolver, DirectiveResolver, PipeResolver, SummaryResolver, ElementSchemaRegistry, DirectiveNormalizer, Console, [Optional, StaticSymbolCache], CompileReflector, [Optional, ERROR_COLLECTOR_TOKEN]]}, DEFAULT_PACKAGE_URL_PROVIDER, // StyleCompiler {provide: StyleCompiler, deps: [UrlResolver]}, // View compiler {provide: ViewCompiler, deps: [CompileReflector]}, // ng module compiler {provide: NgModuleCompiler, deps: [CompileReflector]}, // Compiler configuration items {provide: CompilerConfig, useValue: New CompilerConfig()}, {// Compiler injection provide: Compiler, // here also a core useClass: CompilerImpl, deps: [ Injector, CompileMetadataResolver, TemplateParser, StyleCompiler, ViewCompiler, NgModuleCompiler, SummaryResolver, CompileReflector, CompilerConfig, Console ] }, // dom schema { provide: DomElementSchemaRegistry, deps: []}, // Element schema {provide: ElementSchemaRegistry, useExisting: DomElementSchemaRegistry}, // URL parse {provide: UrlResolver, deps: [PACKAGE_ROOT_URL]}, // dirctive parsing {provide: DirectiveResolver, deps: [CompileReflector]}, // pipe parse {provide: PipeResolver, deps: [CompileReflector]}, // ng module parse {provide: NgModuleResolver, deps: [CompileReflector] } ];Copy the code

Let’s look at his other two cores

  • JitReflector
  • CompilerImpl

JitReflector

export class JitReflector implements CompileReflector {
  private reflectionCapabilities: ReflectionCapabilities;
  constructor() {/ / @ presents/core - > ɵ ReflectionCapabilities enclosing ReflectionCapabilities = new ReflectionCapabilities (); } parameters(typeOrFunc: any): any[][] {
    return this.reflectionCapabilities.parameters(typeOrFunc);
  }
  annotations(typeOrFunc: any): any[] {
    return this.reflectionCapabilities.annotations(typeOrFunc);
  }
  shallowAnnotations(typeOrFunc: any): any[] {
    throw new Error('Not supported in JIT mode');
  }
  tryAnnotations(typeOrFunc: any): any[] {
    return this.annotations(typeOrFunc);
  }
  propMetadata(
    typeOrFunc: any
  ): {
    [key: string]: any[];
  } {
    return this.reflectionCapabilities.propMetadata(typeOrFunc); } // Parse the lifecycle hook hasLifecycleHook(type: any, lcProperty: string): boolean {
    return this.reflectionCapabilities.hasLifecycleHook(type, lcProperty);
  }
  guards(
    typeOrFunc: any
  ): {
    [key: string]: any;
  } {
    return this.reflectionCapabilities.guards(typeOrFunc); } // componentModuleUrl(type: any, cmpMetadata: Component): string {
    const moduleId = cmpMetadata.moduleId;
    if (typeof moduleId === 'string') {
      const scheme = getUrlScheme(moduleId);
      return scheme ? moduleId : `package:${moduleId}${MODULE_SUFFIX}`;
    } else if(moduleId ! == null && moduleId ! == void 0) { throw syntaxError( `moduleId should be a stringin "${stringify(type)}". `); }return`. /${stringify(type)}`;
  }
  resolveExternalReference(ref: ExternalReference): any {
    return builtinExternalReferences.get(ref) || ref.runtime; }}Copy the code

CompilerImpl

export class CompilerImpl implements Compiler {
  private _delegate: JitCompiler;
  public readonly injector: Injector;
  constructor(
    injector: Injector,
    private _metadataResolver: CompileMetadataResolver,
    templateParser: TemplateParser,
    styleCompiler: StyleCompiler,
    viewCompiler: ViewCompiler,
    ngModuleCompiler: NgModuleCompiler,
    summaryResolver: SummaryResolver<Type<any>>,
    compileReflector: CompileReflector,
    compilerConfig: CompilerConfig,
    console: Console
  ) {
    this._delegate = new JitCompiler(
      _metadataResolver,
      templateParser,
      styleCompiler,
      viewCompiler,
      ngModuleCompiler,
      summaryResolver,
      compileReflector,
      compilerConfig,
      console,
      this.getExtraNgModuleProviders.bind(this)
    );
    this.injector = injector;
  }

  private getExtraNgModuleProviders() {
    return[ this._metadataResolver.getProviderMetadata( new ProviderMeta(Compiler, { useValue: this }) ) ]; } // compileModuleSync<T>(moduleType: Type<T>): NgModuleFactory<T> {return this._delegate.compileModuleSync(moduleType) as NgModuleFactory<T>;
  }
  compileModuleAsync<T>(moduleType: Type<T>): Promise<NgModuleFactory<T>> {
    return this._delegate.compileModuleAsync(moduleType) as Promise<
      NgModuleFactory<T>
    >;
  }
  compileModuleAndAllComponentsSync<T>(
    moduleType: Type<T>
  ): ModuleWithComponentFactories<T> {
    const result = this._delegate.compileModuleAndAllComponentsSync(moduleType);
    return {
      ngModuleFactory: result.ngModuleFactory as NgModuleFactory<T>,
      componentFactories: result.componentFactories as ComponentFactory<any>[]
    };
  }
  compileModuleAndAllComponentsAsync<T>(
    moduleType: Type<T>
  ): Promise<ModuleWithComponentFactories<T>> {
    return this._delegate
      .compileModuleAndAllComponentsAsync(moduleType)
      .then(result => ({
        ngModuleFactory: result.ngModuleFactory as NgModuleFactory<T>,
        componentFactories: result.componentFactories as ComponentFactory<any>[]
      }));
  }
  loadAotSummaries(summaries: () => any[]) {
    this._delegate.loadAotSummaries(summaries);
  }
  hasAotSummary(ref: Type<any>): boolean {
    return this._delegate.hasAotSummary(ref);
  }
  getComponentFactory<T>(component: Type<T>): ComponentFactory<T> {
    return this._delegate.getComponentFactory(component) as ComponentFactory<T>;
  }
  clearCache(): void {
    this._delegate.clearCache();
  }
  clearCacheFor(type: Type<any>) {
    this._delegate.clearCacheFor(type); }}Copy the code

Now let’s debug a few of the core points of the previous analysis, but I’m out of order.

JitReflector->hasLifecycleHook

Life cycle detection!

JitReflector->guards

Routing guard

JitReflector->componentModuleUrl

Gets the path to componentModule, such as./AppComponent

CompilerImpl->compileModuleSync

Asynchronous compilation module

CompilerImpl->compileModuleAsync

Asynchronous compilation module

CompilerImpl->compileModuleAndAllComponentsSync

Compile the component under the module

CompilerImpl->compileModuleAndAllComponentsAsync

Asynchronously compile the component under the module

CompilerImpl->getComponentFactory

Get the ComponentFactory instance

After the project starts, you can save the project instance so that from time to time you just need to!

declare const window: any;

let ref1 = platformBrowserDynamic([])
  .bootstrapModule(AppModule)
  .then(res= > {
    window.meepo = res;
  })
  .catch(err= > console.log(err));
Copy the code

conclusion

Ng code written pretty standard, idle to have nothing to read! The above code is just an excerpt! See @angular/platform-browser-dynamic