refactor(core): change module semantics

This contains major changes to the compiler, bootstrap of the platforms
and test environment initialization.

Main part of #10043
Closes #10164

BREAKING CHANGE:
- Semantics and name of `@AppModule` (now `@NgModule`) changed quite a bit.
  This is actually not breaking as `@AppModules` were not part of rc.4.
  We will have detailed docs on `@NgModule` separately.
- `coreLoadAndBootstrap` and `coreBootstrap` can't be used any more (without migration support).
  Use `bootstrapModule` / `bootstrapModuleFactory` instead.
- All Components listed in routes have to be part of the `declarations` of an NgModule.
  Either directly on the bootstrap module / lazy loaded module, or in an NgModule imported by them.
This commit is contained in:
Tobias Bosch
2016-07-18 03:50:31 -07:00
parent ca16fc29a6
commit 46b212706b
129 changed files with 3580 additions and 3366 deletions

View File

@ -30,13 +30,14 @@ generated code:
main_module.ts
-------------
import {BrowserModule} from '@angular/platform-browser';
import {Component, AppModule, ApplicationRef} from '@angular/core';
import {Component, NgModule, ApplicationRef} from '@angular/core';
@Component(...)
export class MyComponent {}
@AppModule({
modules: [BrowserModule],
@NgModule({
imports: [BrowserModule],
declarations: [MyComponent],
precompile: [MyComponent]
})
export class MainModule {

View File

@ -8,10 +8,7 @@
import {Component} from '@angular/core';
@Component({
selector: 'my-comp',
template: '<div></div>',
})
@Component({selector: 'my-comp', template: '<div></div>', directives: [NextComp]})
export class MultipleComponentsMyComp {
}

View File

@ -1,4 +1,4 @@
<div [attr.array]="[0]" [attr.map]="{a:1}" title="translate me" i18n-title="meaning|desc">{{ctxProp}}</div>
<form><input type="button" [(ngModel)]="ctxProp"/></form>
<form><input type="button" [(ngModel)]="ctxProp" name="first"/></form>
<my-comp *ngIf="ctxBool"></my-comp>
<div *ngFor="let x of ctxArr" [attr.value]="x"></div>

View File

@ -6,8 +6,9 @@
* found in the LICENSE file at https://angular.io/license
*/
import {FORM_DIRECTIVES, NgFor, NgIf} from '@angular/common';
import {NgFor, NgIf} from '@angular/common';
import {Component, Inject} from '@angular/core';
import {FORM_DIRECTIVES} from '@angular/forms';
import {MultipleComponentsMyComp} from './a/multiple_components';

View File

@ -10,4 +10,4 @@ import {browserPlatform} from '@angular/platform-browser';
import {BasicComp} from './basic';
import {MainModuleNgFactory} from './module.ngfactory';
MainModuleNgFactory.create().instance.appRef.bootstrap(BasicComp);
MainModuleNgFactory.create(null).instance.appRef.bootstrap(BasicComp);

View File

@ -6,20 +6,29 @@
* found in the LICENSE file at https://angular.io/license
*/
import {AppModule, ApplicationRef} from '@angular/core';
import {ApplicationRef, NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {AnimateCmp} from './animate';
import {BasicComp} from './basic';
import {CompWithProviders, CompWithReferences} from './features';
import {CompUsingRootModuleDirectiveAndPipe, SomeDirectiveInRootModule, SomeLibModule, SomePipeInRootModule, SomeService} from './module_fixtures';
import {CompWithAnalyzePrecompileProvider, CompWithPrecompile} from './precompile';
import {ProjectingComp} from './projection';
import {CompWithChildQuery} from './queries';
import {CompWithChildQuery, CompWithDirectiveChild} from './queries';
@AppModule({
modules: [BrowserModule],
@NgModule({
declarations: [
SomeDirectiveInRootModule, SomePipeInRootModule, AnimateCmp, BasicComp, CompWithPrecompile,
CompWithAnalyzePrecompileProvider, ProjectingComp, CompWithChildQuery, CompWithDirectiveChild,
CompUsingRootModuleDirectiveAndPipe, CompWithProviders, CompWithReferences
],
imports: [BrowserModule, FormsModule, SomeLibModule],
providers: [SomeService],
precompile: [
AnimateCmp, BasicComp, CompWithPrecompile, CompWithAnalyzePrecompileProvider, ProjectingComp,
CompWithChildQuery
CompWithChildQuery, CompUsingRootModuleDirectiveAndPipe
]
})
export class MainModule {

View File

@ -7,7 +7,7 @@
*/
import {LowerCasePipe, NgIf} from '@angular/common';
import {ANALYZE_FOR_PRECOMPILE, AppModule, Component, ComponentFactoryResolver, Directive, Inject, Injectable, Input, OpaqueToken, Pipe} from '@angular/core';
import {ANALYZE_FOR_PRECOMPILE, Component, ComponentFactoryResolver, Directive, Inject, Injectable, Input, NgModule, OpaqueToken, Pipe} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
@Injectable()
@ -16,50 +16,37 @@ export class SomeService {
}
@Injectable()
export class NestedService {
export class ServiceUsingLibModule {
}
@Directive({selector: '[someDir]', host: {'[title]': 'someDir'}})
export class SomeDirective {
export class SomeDirectiveInRootModule {
@Input()
someDir: string;
}
@Directive({selector: '[someDir]', host: {'[title]': 'someDir'}})
export class SomeDirectiveInLibModule {
@Input()
someDir: string;
}
@Pipe({name: 'somePipe'})
export class SomePipe {
export class SomePipeInRootModule {
transform(value: string): any { return `transformed ${value}`; }
}
@Component({selector: 'cmp', template: `<div [someDir]="'someValue' | somePipe"></div>`})
export class SomeComp {
constructor() {}
@Pipe({name: 'somePipe'})
export class SomePipeInLibModule {
transform(value: string): any { return `transformed ${value}`; }
}
@Component({selector: 'parent', template: `<cmp></cmp>`, directives: [SomeComp]})
export class ParentComp {
@Component({selector: 'comp', template: `<div [someDir]="'someValue' | somePipe"></div>`})
export class CompUsingRootModuleDirectiveAndPipe {
}
@AppModule({providers: [NestedService]})
export class NestedModule {
}
@AppModule({
directives: [SomeDirective],
pipes: [SomePipe],
providers: [SomeService],
precompile: [SomeComp],
modules: [NestedModule, BrowserModule]
})
export class SomeModule {
}
@AppModule({
directives: [SomeDirective],
pipes: [SomePipe],
precompile: [ParentComp],
modules: [BrowserModule]
})
export class SomeModuleUsingParentComp {
@Component({selector: 'comp', template: `<div [someDir]="'someValue' | somePipe"></div>`})
export class CompUsingLibModuleDirectiveAndPipe {
}
export const SOME_TOKEN = new OpaqueToken('someToken');
@ -71,7 +58,13 @@ export function provideValueWithPrecompile(value: any) {
];
}
@AppModule({providers: [provideValueWithPrecompile([{a: 'b', component: SomeComp}])]})
export class SomeModuleWithAnalyzePrecompileProvider {
constructor(@Inject(SOME_TOKEN) public providedValue: any) {}
@NgModule({
declarations: [SomeDirectiveInLibModule, SomePipeInLibModule, CompUsingLibModuleDirectiveAndPipe],
precompile: [CompUsingLibModuleDirectiveAndPipe],
providers: [
ServiceUsingLibModule,
provideValueWithPrecompile([{a: 'b', component: CompUsingLibModuleDirectiveAndPipe}])
],
})
export class SomeLibModule {
}

View File

@ -1,62 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import './init';
import {NestedModule, NestedService, ParentComp, SomeComp, SomeModule, SomeService} from '../src/module_fixtures';
import {SomeModuleNgFactory, SomeModuleUsingParentCompNgFactory, SomeModuleWithAnalyzePrecompileProviderNgFactory} from '../src/module_fixtures.ngfactory';
import {createComponent, createModule} from './util';
describe('AppModule', () => {
it('should support providers', () => {
var moduleRef = createModule(SomeModuleNgFactory);
expect(moduleRef.instance instanceof SomeModule).toBe(true);
expect(moduleRef.injector.get(SomeModule) instanceof SomeModule).toBe(true);
expect(moduleRef.injector.get(SomeService) instanceof SomeService).toBe(true);
});
it('should support precompile components', () => {
var moduleRef = createModule(SomeModuleNgFactory);
var cf = moduleRef.componentFactoryResolver.resolveComponentFactory(SomeComp);
expect(cf.componentType).toBe(SomeComp);
var compRef = cf.create(moduleRef.injector);
expect(compRef.instance instanceof SomeComp).toBe(true);
});
it('should support precompile via the ANALYZE_FOR_PRECOMPILE provider and function providers in components',
() => {
const moduleRef = createModule(SomeModuleWithAnalyzePrecompileProviderNgFactory);
const cf = moduleRef.componentFactoryResolver.resolveComponentFactory(SomeComp);
expect(cf.componentType).toBe(SomeComp);
// check that the function call that created the provider for ANALYZE_FOR_PRECOMPILE worked.
expect(moduleRef.instance.providedValue).toEqual([{a: 'b', component: SomeComp}]);
});
it('should support module directives and pipes', () => {
var compFixture = createComponent(SomeComp, SomeModuleNgFactory);
compFixture.detectChanges();
var debugElement = compFixture.debugElement;
expect(debugElement.children[0].properties['title']).toBe('transformed someValue');
});
it('should support module directives and pipes on nested components', () => {
var compFixture = createComponent(ParentComp, SomeModuleUsingParentCompNgFactory);
compFixture.detectChanges();
var debugElement = compFixture.debugElement;
debugElement = debugElement.children[0];
expect(debugElement.children[0].properties['title']).toBe('transformed someValue');
});
it('should support child moduless', () => {
var moduleRef = createModule(SomeModuleNgFactory);
expect(moduleRef.instance instanceof SomeModule).toBe(true);
expect(moduleRef.injector.get(NestedModule) instanceof NestedModule).toBe(true);
expect(moduleRef.injector.get(NestedService) instanceof NestedService).toBe(true);
});
});

View File

@ -0,0 +1,63 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import './init';
import {MainModule} from '../src/module';
import {CompUsingLibModuleDirectiveAndPipe, CompUsingRootModuleDirectiveAndPipe, SOME_TOKEN, ServiceUsingLibModule, SomeLibModule, SomeService} from '../src/module_fixtures';
import {createComponent, createModule} from './util';
describe('NgModule', () => {
it('should support providers', () => {
const moduleRef = createModule();
expect(moduleRef.instance instanceof MainModule).toBe(true);
expect(moduleRef.injector.get(MainModule) instanceof MainModule).toBe(true);
expect(moduleRef.injector.get(SomeService) instanceof SomeService).toBe(true);
});
it('should support precompile components', () => {
const moduleRef = createModule();
const cf = moduleRef.componentFactoryResolver.resolveComponentFactory(
CompUsingRootModuleDirectiveAndPipe);
expect(cf.componentType).toBe(CompUsingRootModuleDirectiveAndPipe);
const compRef = cf.create(moduleRef.injector);
expect(compRef.instance instanceof CompUsingRootModuleDirectiveAndPipe).toBe(true);
});
it('should support precompile via the ANALYZE_FOR_PRECOMPILE provider and function providers in components',
() => {
const moduleRef = createModule();
const cf = moduleRef.componentFactoryResolver.resolveComponentFactory(
CompUsingRootModuleDirectiveAndPipe);
expect(cf.componentType).toBe(CompUsingRootModuleDirectiveAndPipe);
// check that the function call that created the provider for ANALYZE_FOR_PRECOMPILE worked.
expect(moduleRef.injector.get(SOME_TOKEN)).toEqual([
{a: 'b', component: CompUsingLibModuleDirectiveAndPipe}
]);
});
it('should support module directives and pipes', () => {
const compFixture = createComponent(CompUsingRootModuleDirectiveAndPipe);
compFixture.detectChanges();
const debugElement = compFixture.debugElement;
expect(debugElement.children[0].properties['title']).toBe('transformed someValue');
});
it('should support module directives and pipes on lib modules', () => {
const compFixture = createComponent(CompUsingLibModuleDirectiveAndPipe);
compFixture.detectChanges();
const debugElement = compFixture.debugElement;
expect(debugElement.children[0].properties['title']).toBe('transformed someValue');
expect(debugElement.injector.get(SomeLibModule) instanceof SomeLibModule).toBe(true);
expect(debugElement.injector.get(ServiceUsingLibModule) instanceof ServiceUsingLibModule)
.toBe(true);
});
});

View File

@ -6,23 +6,19 @@
* found in the LICENSE file at https://angular.io/license
*/
import {AppModuleFactory, AppModuleRef, bootstrapModuleFactory} from '@angular/core';
import {NgModuleFactory, NgModuleRef, bootstrapModuleFactory} from '@angular/core';
import {ComponentFixture} from '@angular/core/testing';
import {serverPlatform} from '@angular/platform-server';
import {MainModule} from '../src/module';
import {MainModuleNgFactory} from '../src/module.ngfactory';
export function createModule<M>(factory: AppModuleFactory<M>): AppModuleRef<M> {
return bootstrapModuleFactory(factory, serverPlatform());
export function createModule(): NgModuleRef<MainModule> {
return bootstrapModuleFactory(MainModuleNgFactory, serverPlatform());
}
export function createComponent<C>(
comp: {new (...args: any[]): C},
moduleFactory: AppModuleFactory<any> = null): ComponentFixture<C> {
if (!moduleFactory) {
moduleFactory = MainModuleNgFactory;
}
const moduleRef = createModule(moduleFactory);
export function createComponent<C>(comp: {new (...args: any[]): C}): ComponentFixture<C> {
const moduleRef = createModule();
const compRef =
moduleRef.componentFactoryResolver.resolveComponentFactory(comp).create(moduleRef.injector);
return new ComponentFixture(compRef, null, null);

View File

@ -11,12 +11,12 @@
* Intended to be used in a build step.
*/
import * as compiler from '@angular/compiler';
import {AppModuleMetadata, ComponentMetadata, ViewEncapsulation} from '@angular/core';
import {ComponentMetadata, NgModuleMetadata, ViewEncapsulation} from '@angular/core';
import {AngularCompilerOptions} from '@angular/tsc-wrapped';
import * as path from 'path';
import * as ts from 'typescript';
import {AppModuleCompiler, CompileMetadataResolver, DirectiveNormalizer, DomElementSchemaRegistry, HtmlParser, Lexer, Parser, StyleCompiler, TemplateParser, TypeScriptEmitter, ViewCompiler} from './compiler_private';
import {CompileMetadataResolver, DirectiveNormalizer, DomElementSchemaRegistry, HtmlParser, Lexer, NgModuleCompiler, Parser, StyleCompiler, TemplateParser, TypeScriptEmitter, ViewCompiler} from './compiler_private';
import {ReflectorHost, ReflectorHostContext} from './reflector_host';
import {StaticAndDynamicReflectionCapabilities} from './static_reflection_capabilities';
import {StaticReflector, StaticSymbol} from './static_reflector';
@ -39,7 +39,7 @@ export class CodeGenerator {
private readFileMetadata(absSourcePath: string): FileMetadata {
const moduleMetadata = this.staticReflector.getModuleMetadata(absSourcePath);
const result: FileMetadata = {components: [], appModules: [], fileUrl: absSourcePath};
const result: FileMetadata = {components: [], ngModules: [], fileUrl: absSourcePath};
if (!moduleMetadata) {
console.log(`WARNING: no metadata found for ${absSourcePath}`);
return result;
@ -57,8 +57,8 @@ export class CodeGenerator {
const staticType = this.reflectorHost.findDeclaration(absSourcePath, symbol, absSourcePath);
const annotations = this.staticReflector.annotations(staticType);
annotations.forEach((annotation) => {
if (annotation instanceof AppModuleMetadata) {
result.appModules.push(staticType);
if (annotation instanceof NgModuleMetadata) {
result.ngModules.push(staticType);
} else if (annotation instanceof ComponentMetadata) {
result.components.push(staticType);
}
@ -86,17 +86,17 @@ export class CodeGenerator {
let filePaths =
this.program.getSourceFiles().map(sf => sf.fileName).filter(f => !GENERATED_FILES.test(f));
let fileMetas = filePaths.map((filePath) => this.readFileMetadata(filePath));
let appModules = fileMetas.reduce((appModules, fileMeta) => {
appModules.push(...fileMeta.appModules);
return appModules;
let ngModules = fileMetas.reduce((ngModules, fileMeta) => {
ngModules.push(...fileMeta.ngModules);
return ngModules;
}, <StaticSymbol[]>[]);
let analyzedAppModules = this.compiler.analyzeModules(appModules);
let analyzedNgModules = this.compiler.analyzeModules(ngModules);
return Promise
.all(fileMetas.map(
(fileMeta) => this.compiler
.compile(
fileMeta.fileUrl, analyzedAppModules, fileMeta.components,
fileMeta.appModules)
fileMeta.fileUrl, analyzedNgModules, fileMeta.components,
fileMeta.ngModules)
.then((generatedModules) => {
generatedModules.forEach((generatedModule) => {
const sourceFile = this.program.getSourceFile(fileMeta.fileUrl);
@ -139,11 +139,12 @@ export class CodeGenerator {
expressionParser, new DomElementSchemaRegistry(), htmlParser,
/*console*/ null, []);
const resolver = new CompileMetadataResolver(
new compiler.NgModuleResolver(staticReflector),
new compiler.DirectiveResolver(staticReflector), new compiler.PipeResolver(staticReflector),
new compiler.ViewResolver(staticReflector), config, staticReflector);
new compiler.ViewResolver(staticReflector), config, /*console*/ null, staticReflector);
const offlineCompiler = new compiler.OfflineCompiler(
resolver, normalizer, tmplParser, new StyleCompiler(urlResolver), new ViewCompiler(config),
new AppModuleCompiler(), new TypeScriptEmitter(reflectorHost));
new NgModuleCompiler(), new TypeScriptEmitter(reflectorHost));
return new CodeGenerator(
options, program, compilerHost, staticReflector, offlineCompiler, reflectorHost);
@ -153,5 +154,5 @@ export class CodeGenerator {
interface FileMetadata {
fileUrl: string;
components: StaticSymbol[];
appModules: StaticSymbol[];
}
ngModules: StaticSymbol[];
}

View File

@ -61,8 +61,8 @@ export var StyleCompiler: typeof _c.StyleCompiler = _c.StyleCompiler;
export type ViewCompiler = _c.ViewCompiler;
export var ViewCompiler: typeof _c.ViewCompiler = _c.ViewCompiler;
export type AppModuleCompiler = _c.AppModuleCompiler;
export var AppModuleCompiler: typeof _c.AppModuleCompiler = _c.AppModuleCompiler;
export type NgModuleCompiler = _c.NgModuleCompiler;
export var NgModuleCompiler: typeof _c.NgModuleCompiler = _c.NgModuleCompiler;
export type TypeScriptEmitter = _c.TypeScriptEmitter;
export var TypeScriptEmitter: typeof _c.TypeScriptEmitter = _c.TypeScriptEmitter;

View File

@ -76,7 +76,7 @@ class Extractor {
for (const symbol of symbols) {
const staticType = this._reflectorHost.findDeclaration(absSourcePath, symbol, absSourcePath);
let directive: compiler.CompileDirectiveMetadata;
directive = this._resolver.maybeGetDirectiveMetadata(<any>staticType);
directive = this._resolver.getDirectiveMetadata(<any>staticType, false);
if (directive && directive.isComponent) {
let promise = this._normalizer.normalizeDirective(directive).asyncResult;
@ -147,8 +147,9 @@ class Extractor {
const normalizer = new DirectiveNormalizer(xhr, urlResolver, htmlParser, config);
const expressionParser = new Parser(new Lexer());
const resolver = new CompileMetadataResolver(
new compiler.NgModuleResolver(staticReflector),
new compiler.DirectiveResolver(staticReflector), new compiler.PipeResolver(staticReflector),
new compiler.ViewResolver(staticReflector), config, staticReflector);
new compiler.ViewResolver(staticReflector), config, /*console*/ null, staticReflector);
// TODO(vicb): handle implicit
const extractor = new MessageExtractor(htmlParser, expressionParser, [], {});

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {AppModuleMetadata, AttributeMetadata, ComponentMetadata, ContentChildMetadata, ContentChildrenMetadata, DirectiveMetadata, HostBindingMetadata, HostListenerMetadata, HostMetadata, InjectMetadata, InjectableMetadata, InputMetadata, OptionalMetadata, OutputMetadata, PipeMetadata, Provider, QueryMetadata, SelfMetadata, SkipSelfMetadata, ViewChildMetadata, ViewChildrenMetadata, ViewQueryMetadata, animate, group, keyframes, sequence, state, style, transition, trigger} from '@angular/core';
import {AttributeMetadata, ComponentMetadata, ContentChildMetadata, ContentChildrenMetadata, DirectiveMetadata, HostBindingMetadata, HostListenerMetadata, HostMetadata, InjectMetadata, InjectableMetadata, InputMetadata, NgModuleMetadata, OptionalMetadata, OutputMetadata, PipeMetadata, Provider, QueryMetadata, SelfMetadata, SkipSelfMetadata, ViewChildMetadata, ViewChildrenMetadata, ViewQueryMetadata, animate, group, keyframes, sequence, state, style, transition, trigger} from '@angular/core';
import {ReflectorReader} from './core_private';
@ -217,7 +217,7 @@ export class StaticReflector implements ReflectorReader {
this.registerDecoratorOrConstructor(
this.host.findDeclaration(coreDecorators, 'Component'), ComponentMetadata);
this.registerDecoratorOrConstructor(
this.host.findDeclaration(coreDecorators, 'AppModule'), AppModuleMetadata);
this.host.findDeclaration(coreDecorators, 'NgModule'), NgModuleMetadata);
// Note: Some metadata classes can be used directly with Provider.deps.
this.registerDecoratorOrConstructor(
@ -619,4 +619,4 @@ function sameSymbol(a: StaticSymbol, b: StaticSymbol): boolean {
function shouldIgnore(value: any): boolean {
return value && value.__symbolic == 'ignore';
}
}