-
Notifications
You must be signed in to change notification settings - Fork 12k
/
export_ngfactory.ts
79 lines (64 loc) · 2.68 KB
/
export_ngfactory.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* @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 { dirname, relative } from 'path';
import * as ts from 'typescript';
import { collectDeepNodes, getFirstNode } from './ast_helpers';
import { AddNodeOperation, StandardTransform, TransformOperation } from './interfaces';
import { makeTransform } from './make_transform';
export function exportNgFactory(
shouldTransform: (fileName: string) => boolean,
getEntryModule: () => { path: string, className: string } | null,
): ts.TransformerFactory<ts.SourceFile> {
const standardTransform: StandardTransform = function (sourceFile: ts.SourceFile) {
const ops: TransformOperation[] = [];
const entryModule = getEntryModule();
if (!shouldTransform(sourceFile.fileName) || !entryModule) {
return ops;
}
// Find all identifiers using the entry module class name.
const entryModuleIdentifiers = collectDeepNodes<ts.Identifier>(sourceFile,
ts.SyntaxKind.Identifier)
.filter(identifier => identifier.text === entryModule.className);
if (entryModuleIdentifiers.length === 0) {
return [];
}
const relativeEntryModulePath = relative(dirname(sourceFile.fileName), entryModule.path);
const normalizedEntryModulePath = `./${relativeEntryModulePath}`.replace(/\\/g, '/');
// Get the module path from the import.
entryModuleIdentifiers.forEach((entryModuleIdentifier) => {
if (!entryModuleIdentifier.parent
|| entryModuleIdentifier.parent.kind !== ts.SyntaxKind.ExportSpecifier) {
return;
}
const exportSpec = entryModuleIdentifier.parent as ts.ExportSpecifier;
const moduleSpecifier = exportSpec.parent
&& exportSpec.parent.parent
&& exportSpec.parent.parent.moduleSpecifier;
if (!moduleSpecifier || moduleSpecifier.kind !== ts.SyntaxKind.StringLiteral) {
return;
}
// Add the transform operations.
const factoryClassName = entryModule.className + 'NgFactory';
const factoryModulePath = normalizedEntryModulePath + '.ngfactory';
const namedExports = ts.createNamedExports([ts.createExportSpecifier(undefined,
ts.createIdentifier(factoryClassName))]);
const newImport = ts.createExportDeclaration(undefined, undefined, namedExports,
ts.createLiteral(factoryModulePath));
const firstNode = getFirstNode(sourceFile);
if (firstNode) {
ops.push(new AddNodeOperation(
sourceFile,
firstNode,
newImport,
));
}
});
return ops;
};
return makeTransform(standardTransform);
}