|
1 | 1 | import { JSCodeshift, Node, valueType } from "./types/NodePath";
|
2 | 2 | import * as validateIdentifier from "./validate-identifier";
|
3 | 3 |
|
| 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 | + |
4 | 15 | /**
|
5 | 16 | *
|
6 | 17 | * Traverse safely over a path object for array for paths
|
@@ -629,31 +640,23 @@ function parseMerge(j: JSCodeshift, ast: Node, value: string[], action: string):
|
629 | 640 | right: j.callExpression(j.identifier("merge"), [j.identifier(configIdentifier), exportsDecl.pop()]),
|
630 | 641 | type: "AssignmentExpression"
|
631 | 642 | };
|
| 643 | + |
632 | 644 | (p.value as Node).body[bodyLength - 1] = newVal;
|
633 | 645 | return false; // TODO: debug later
|
634 | 646 | }
|
635 | 647 |
|
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 | + }) |
648 | 655 | }
|
649 | 656 |
|
650 | 657 | if (value) {
|
651 | 658 | 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); |
657 | 660 | return ast.find(j.Program).filter((p: Node): boolean => createMergeProperty(p, configIdentifier));
|
658 | 661 | } else {
|
659 | 662 | return ast;
|
|
0 commit comments