Skip to content

Commit a89645a

Browse files
committedMay 31, 2019
chore: create isImportPresent
1 parent 6a7e662 commit a89645a

File tree

2 files changed

+21
-17
lines changed

2 files changed

+21
-17
lines changed
 

‎packages/utils/ast-utils.ts

+20-17
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,17 @@
11
import { JSCodeshift, Node, valueType } from "./types/NodePath";
22
import * as validateIdentifier from "./validate-identifier";
33

4+
5+
function isImportPresent (j: JSCodeshift, ast: Node, path: string): boolean {
6+
let isPresent: boolean = false;
7+
ast.find(j.CallExpression).forEach(callExp => {
8+
if ((callExp.value as Node).callee.name === 'require' && (callExp.value as Node).arguments[0].value === path) {
9+
isPresent = true;
10+
}
11+
})
12+
return isPresent;
13+
}
14+
415
/**
516
*
617
* Traverse safely over a path object for array for paths
@@ -629,31 +640,23 @@ function parseMerge(j: JSCodeshift, ast: Node, value: string[], action: string):
629640
right: j.callExpression(j.identifier("merge"), [j.identifier(configIdentifier), exportsDecl.pop()]),
630641
type: "AssignmentExpression"
631642
};
643+
632644
(p.value as Node).body[bodyLength - 1] = newVal;
633645
return false; // TODO: debug later
634646
}
635647

636-
function addMergeImports(ast: Node, mergeImports: string[]) {
637-
ast.find(j.Program).filter((program: Node): boolean => {
638-
mergeImports.forEach(
639-
(imp: string): void => {
640-
if ((program.value as Node).body.indexOf(imp) === -1){
641-
(program.value as Node).body.splice(-1, 0, imp);
642-
}
643-
}
644-
)
645-
return false;
646-
});
647-
return ast;
648+
function addMergeImports(configIdentifier: string, configPath: string) {
649+
ast.find(j.Program).forEach(p => {
650+
if (!isImportPresent(j, ast, 'webpack-merge')) {
651+
(p.value as Node).body.splice(-1, 0, `const merge = require('webpack-merge')`);
652+
}
653+
(p.value as Node).body.splice(-1, 0, `const ${configIdentifier} = require('${configPath}')`);
654+
})
648655
}
649656

650657
if (value) {
651658
const [configIdentifier, configPath] = value;
652-
const mergeImports = [
653-
`const ${configIdentifier} = require('${configPath}')`,
654-
`const merge = require('webpack-merge')`
655-
];
656-
ast.replaceWith(addMergeImports(ast, mergeImports));
659+
addMergeImports(configIdentifier, configPath);
657660
return ast.find(j.Program).filter((p: Node): boolean => createMergeProperty(p, configIdentifier));
658661
} else {
659662
return ast;

‎packages/utils/types/NodePath.ts

+1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ export interface Node extends Object {
22
id?: {
33
name: string;
44
};
5+
callee?: Node;
56
arguments?: Node[];
67
body?: Node[];
78
elements?: Node[];

0 commit comments

Comments
 (0)
Please sign in to comment.