-
-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
NgModulesAnalyzer.ts
59 lines (54 loc) · 1.6 KB
/
NgModulesAnalyzer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { NgModule } from '@angular/core';
/**
* Avoid component redeclaration
*
* Checks recursively if the component has already been declared in all import Module
*/
export const isComponentAlreadyDeclaredInModules = (
componentToFind: any,
moduleDeclarations: any[],
moduleImports: any[]
): boolean => {
if (
moduleDeclarations &&
moduleDeclarations.some((declaration) => declaration === componentToFind)
) {
// Found component in declarations array
return true;
}
if (!moduleImports) {
return false;
}
return moduleImports.some((importItem) => {
const extractedNgModuleMetadata = extractNgModuleMetadata(importItem);
if (!extractedNgModuleMetadata) {
// Not an NgModule
return false;
}
return isComponentAlreadyDeclaredInModules(
componentToFind,
extractedNgModuleMetadata.declarations,
extractedNgModuleMetadata.imports
);
});
};
const extractNgModuleMetadata = (importItem: any): NgModule => {
const target = importItem && importItem.ngModule ? importItem.ngModule : importItem;
const decoratorKey = '__annotations__';
const decorators: any[] =
Reflect &&
Reflect.getOwnPropertyDescriptor &&
Reflect.getOwnPropertyDescriptor(target, decoratorKey)
? Reflect.getOwnPropertyDescriptor(target, decoratorKey).value
: target[decoratorKey];
if (!decorators || decorators.length === 0) {
return null;
}
const ngModuleDecorator: NgModule | undefined = decorators.find(
(decorator) => decorator instanceof NgModule
);
if (!ngModuleDecorator) {
return null;
}
return ngModuleDecorator;
};