-
-
Notifications
You must be signed in to change notification settings - Fork 295
/
Copy pathns-module-factory-loader.ts
82 lines (63 loc) · 2.4 KB
/
ns-module-factory-loader.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
80
81
82
import {
Injectable,
Compiler,
NgModuleFactory,
NgModuleFactoryLoader
} from "@angular/core";
import { path, knownFolders } from "file-system";
declare var System: any;
const SEPARATOR = "#";
const FACTORY_CLASS_SUFFIX = "NgFactory";
const FACTORY_PATH_SUFFIX = ".ngfactory";
@Injectable()
export class NsModuleFactoryLoader implements NgModuleFactoryLoader {
private offlineMode: boolean;
constructor(private compiler: Compiler) {
this.offlineMode = compiler instanceof Compiler;
}
load(path: string): Promise<NgModuleFactory<any>> {
let {modulePath, exportName} = this.splitPath(path);
if (this.offlineMode) {
return this.loadFactory(modulePath, exportName);
} else {
return this.loadAndCompile(modulePath, exportName);
}
}
private loadFactory(modulePath: string, exportName: string): Promise<NgModuleFactory<any>> {
modulePath = factoryModulePath(modulePath);
exportName = factoryExportName(exportName);
return System.import(modulePath)
.then((module: any) => module[exportName])
.then((factory: any) => checkNotEmpty(factory, modulePath, exportName));
}
private loadAndCompile(modulePath: string, exportName: string): Promise<NgModuleFactory<any>> {
modulePath = getAbsolutePath(modulePath);
let loadedModule = require(modulePath)[exportName];
checkNotEmpty(loadedModule, modulePath, exportName);
return Promise.resolve(this.compiler.compileModuleAsync(loadedModule));
}
private splitPath(path: string): {modulePath: string, exportName: string} {
let [modulePath, exportName] = path.split(SEPARATOR);
if (typeof exportName === "undefined") {
exportName = "default";
}
return {modulePath, exportName};
}
}
function getAbsolutePath(relativePath: string) {
return path.normalize(path.join(knownFolders.currentApp().path, relativePath));
}
function factoryModulePath(modulePath) {
return `${modulePath}${FACTORY_PATH_SUFFIX}`;
}
function factoryExportName(exportName) {
return exportName === "default" ?
exportName :
`${exportName}${FACTORY_CLASS_SUFFIX}`;
}
function checkNotEmpty(value: any, modulePath: string, exportName: string): any {
if (!value) {
throw new Error(`Cannot find '${exportName}' in '${modulePath}'`);
}
return value;
}