UNPKG

2.33 kBJavaScriptView Raw
1'use strict';
2
3const t = require('babel-types');
4
5function getSourceModule(itemName, itemBinding) {
6 // TODO: deal with reassignment
7 if (!itemBinding.constant) {
8 return null;
9 }
10
11 let sourceModule;
12 let imported;
13 let local;
14 let destructured;
15 let usesImportSyntax = false;
16
17 if (
18 // import x from 'y';
19 t.isImportDefaultSpecifier(itemBinding.path.node) ||
20 // import {x} from 'y';
21 t.isImportSpecifier(itemBinding.path.node)
22 ) {
23 if (
24 t.isImportDeclaration(itemBinding.path.parent) &&
25 t.isStringLiteral(itemBinding.path.parent.source)
26 ) {
27 sourceModule = itemBinding.path.parent.source.value;
28 local = itemBinding.path.node.local.name;
29 usesImportSyntax = true;
30 if (itemBinding.path.node.imported) {
31 imported = itemBinding.path.node.imported.name;
32 destructured = true;
33 } else {
34 imported = itemBinding.path.node.local.name;
35 destructured = false;
36 }
37 }
38 } else if (
39 t.isVariableDeclarator(itemBinding.path.node) &&
40 t.isCallExpression(itemBinding.path.node.init) &&
41 t.isIdentifier(itemBinding.path.node.init.callee) &&
42 itemBinding.path.node.init.callee.name === 'require' &&
43 itemBinding.path.node.init.arguments.length === 1 &&
44 t.isStringLiteral(itemBinding.path.node.init.arguments[0])
45 ) {
46 sourceModule = itemBinding.path.node.init.arguments[0].value;
47
48 if (t.isIdentifier(itemBinding.path.node.id)) {
49 local = itemBinding.path.node.id.name;
50 imported = itemBinding.path.node.id.name;
51 destructured = false;
52 } else if (t.isObjectPattern(itemBinding.path.node.id)) {
53 // TODO: better way to get ObjectProperty
54 const objProp = itemBinding.path.node.id.properties.find(
55 p => t.isIdentifier(p.value) && p.value.name === itemName
56 );
57
58 if (!objProp) {
59 console.error('could not find prop with value `%s`', itemName);
60 return null;
61 }
62
63 local = objProp.value.name;
64 imported = objProp.key.name;
65 destructured = true;
66 } else {
67 console.error('Unhandled id type: %s', itemBinding.path.node.id.type);
68 return null;
69 }
70 } else {
71 return null;
72 }
73
74 return {
75 sourceModule,
76 imported,
77 local,
78 destructured,
79 usesImportSyntax,
80 };
81}
82
83module.exports = getSourceModule;