feat: change @Injectable() to support tree-shakeable tokens (#22005)

This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.

Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".

Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.

Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.

Additionally, this commit adds several unit and integration tests of various
flavors to test this change.

PR Close #22005
This commit is contained in:
Alex Rickabaugh
2018-02-02 10:33:48 -08:00
committed by Miško Hevery
parent 2d5e7d1b52
commit 235a235fab
58 changed files with 1753 additions and 228 deletions

View File

@ -7,11 +7,11 @@
*/
import {resolveForwardRef} from '../di/forward_ref';
import {Injector} from '../di/injector';
import {InjectFlags, Injector, setCurrentInjector} from '../di/injector';
import {NgModuleRef} from '../linker/ng_module_factory';
import {stringify} from '../util';
import {DepDef, DepFlags, NgModuleData, NgModuleDefinition, NgModuleProviderDef, NodeFlags} from './types';
import {DepDef, DepFlags, InjectableDef, NgModuleData, NgModuleDefinition, NgModuleProviderDef, NodeFlags} from './types';
import {splitDepsDsl, tokenKey} from './util';
const UNDEFINED_VALUE = new Object();
@ -19,6 +19,12 @@ const UNDEFINED_VALUE = new Object();
const InjectorRefTokenKey = tokenKey(Injector);
const NgModuleRefTokenKey = tokenKey(NgModuleRef);
export function injectableDef(scope: any, factory: () => any): InjectableDef {
return {
scope, factory,
};
}
export function moduleProvideDef(
flags: NodeFlags, token: any, value: any,
deps: ([DepFlags, any] | any)[]): NgModuleProviderDef {
@ -90,10 +96,32 @@ export function resolveNgModuleDep(
_createProviderInstance(data, providerDef);
}
return providerInstance === UNDEFINED_VALUE ? undefined : providerInstance;
} else if (depDef.token.ngInjectableDef && targetsModule(data, depDef.token.ngInjectableDef)) {
const injectableDef = depDef.token.ngInjectableDef as InjectableDef;
const key = tokenKey;
const index = data._providers.length;
data._def.providersByKey[depDef.tokenKey] = {
flags: NodeFlags.TypeFactoryProvider | NodeFlags.LazyProvider,
value: injectableDef.factory,
deps: [], index,
token: depDef.token,
};
const former = setCurrentInjector(data);
try {
data._providers[index] = UNDEFINED_VALUE;
return (
data._providers[index] =
_createProviderInstance(data, data._def.providersByKey[depDef.tokenKey]));
} finally {
setCurrentInjector(former);
}
}
return data._parent.get(depDef.token, notFoundValue);
}
function targetsModule(ngModule: NgModuleData, def: InjectableDef): boolean {
return def.scope != null && ngModule._def.modules.indexOf(def.scope) > -1;
}
function _createProviderInstance(ngModule: NgModuleData, providerDef: NgModuleProviderDef): any {
let injectable: any;

View File

@ -346,50 +346,56 @@ export function resolveDep(
elDef = elDef.parent !;
}
while (view) {
let searchView: ViewData|null = view;
while (searchView) {
if (elDef) {
switch (tokenKey) {
case RendererV1TokenKey: {
const compView = findCompView(view, elDef, allowPrivateServices);
const compView = findCompView(searchView, elDef, allowPrivateServices);
return createRendererV1(compView);
}
case Renderer2TokenKey: {
const compView = findCompView(view, elDef, allowPrivateServices);
const compView = findCompView(searchView, elDef, allowPrivateServices);
return compView.renderer;
}
case ElementRefTokenKey:
return new ElementRef(asElementData(view, elDef.nodeIndex).renderElement);
return new ElementRef(asElementData(searchView, elDef.nodeIndex).renderElement);
case ViewContainerRefTokenKey:
return asElementData(view, elDef.nodeIndex).viewContainer;
return asElementData(searchView, elDef.nodeIndex).viewContainer;
case TemplateRefTokenKey: {
if (elDef.element !.template) {
return asElementData(view, elDef.nodeIndex).template;
return asElementData(searchView, elDef.nodeIndex).template;
}
break;
}
case ChangeDetectorRefTokenKey: {
let cdView = findCompView(view, elDef, allowPrivateServices);
let cdView = findCompView(searchView, elDef, allowPrivateServices);
return createChangeDetectorRef(cdView);
}
case InjectorRefTokenKey:
return createInjector(view, elDef);
return createInjector(searchView, elDef);
default:
const providerDef =
(allowPrivateServices ? elDef.element !.allProviders :
elDef.element !.publicProviders) ![tokenKey];
if (providerDef) {
let providerData = asProviderData(view, providerDef.nodeIndex);
let providerData = asProviderData(searchView, providerDef.nodeIndex);
if (!providerData) {
providerData = {instance: _createProviderInstance(view, providerDef)};
view.nodes[providerDef.nodeIndex] = providerData as any;
providerData = {instance: _createProviderInstance(searchView, providerDef)};
searchView.nodes[providerDef.nodeIndex] = providerData as any;
}
return providerData.instance;
}
}
}
allowPrivateServices = isComponentView(view);
elDef = viewParentEl(view) !;
view = view.parent !;
allowPrivateServices = isComponentView(searchView);
elDef = viewParentEl(searchView) !;
searchView = searchView.parent !;
if (depDef.flags & DepFlags.Self) {
searchView = null;
}
}
const value = startView.root.injector.get(depDef.token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR);

View File

@ -8,7 +8,7 @@
import {ApplicationRef} from '../application_ref';
import {ChangeDetectorRef} from '../change_detection/change_detection';
import {Injector} from '../di/injector';
import {InjectFlags, Injector} from '../di/injector';
import {ComponentFactory, ComponentRef} from '../linker/component_factory';
import {ComponentFactoryBoundToModule, ComponentFactoryResolver} from '../linker/component_factory_resolver';
import {ElementRef} from '../linker/element_ref';
@ -480,6 +480,7 @@ class NgModuleRef_ implements NgModuleData, InternalNgModuleRef<any> {
private _destroyed: boolean = false;
/** @internal */
_providers: any[];
/** @internal */
_modules: any[];
readonly injector: Injector = this;
@ -490,9 +491,16 @@ class NgModuleRef_ implements NgModuleData, InternalNgModuleRef<any> {
initNgModule(this);
}
get(token: any, notFoundValue: any = Injector.THROW_IF_NOT_FOUND): any {
get(token: any, notFoundValue: any = Injector.THROW_IF_NOT_FOUND,
injectFlags: InjectFlags = InjectFlags.Default): any {
let flags = DepFlags.None;
if (injectFlags & InjectFlags.SkipSelf) {
flags |= DepFlags.SkipSelf;
} else if (injectFlags & InjectFlags.Self) {
flags |= DepFlags.Self;
}
return resolveNgModuleDep(
this, {token: token, tokenKey: tokenKey(token), flags: DepFlags.None}, notFoundValue);
this, {token: token, tokenKey: tokenKey(token), flags: flags}, notFoundValue);
}
get instance() { return this.get(this._moduleType); }

View File

@ -292,7 +292,8 @@ export const enum DepFlags {
None = 0,
SkipSelf = 1 << 0,
Optional = 1 << 1,
Value = 2 << 2,
Self = 1 << 2,
Value = 1 << 3,
}
export interface InjectableDef {