-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodule-transform.js
More file actions
60 lines (49 loc) · 2.09 KB
/
module-transform.js
File metadata and controls
60 lines (49 loc) · 2.09 KB
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
import jscodeshift, { ImportSpecifier } from 'jscodeshift';
const moduleName = 'Test1Module';
const modulePath = './test0/test1.module';
class NoModulesError extends Error {
constructor() {
super(`No NgModules found in app module.
Are you sure you have the correct path registered in 'appModulePath'?`)
}
}
class TooManyModulesError extends Error {
constructor() {
super(`More than one NgModule found in app module.
There should be only one.`)
}
}
/**
* @param {string} source
* @param {string} moduleName - ex 'MyModule'
* @param {string} modulePath - module path relative to appModulePath, ex './thing/my.module'
*/
export function addModule(sourceText, moduleName, modulePath) {
const source = jscodeshift.withParser('flow')(sourceText);
const ngModules = source
.find(jscodeshift.ClassDeclaration, path => path.decorators.some(decorator => decorator.expression.callee.name === 'NgModule'));
if(ngModules.size() === 0) {
throw new NoModulesError();
}
if(ngModules.size() > 1) {
throw new TooManyModulesError();
}
const ngModuleClass = ngModules.get();
const ngModule = ngModuleClass.value.decorators.find(decorator => decorator.expression.callee.name === 'NgModule');
const imports = ngModule.expression.arguments[0].properties.find(prop => prop.key.name === 'imports');
if(!imports) {
console.info('No \'imports\' property? Strange..');
// TODO: create
}
// Push module to `imports` array
const MyModuleIdentifier = jscodeshift.identifier(moduleName);
imports.value.elements.push(MyModuleIdentifier);
const existingImports = source.find(ImportSpecifier);
if(existingImports.size() === 0) {
// TODO: Must be using some other module format
}
const MyModuleImport = jscodeshift.importDeclaration([jscodeshift.importSpecifier(jscodeshift.identifier(moduleName))], jscodeshift.literal(modulePath));
// Insert after last `import {...} from '...'` statement
jscodeshift(existingImports.at(-1).get().parent.insertAfter(MyModuleImport));
return source.toSource({quote: 'single'});
}