resolveToModule.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import getMemberExpressionRoot from './getMemberExpressionRoot.js';
  2. import resolveToValue from './resolveToValue.js';
  3. /**
  4. * Given a path (e.g. call expression, member expression or identifier),
  5. * this function tries to find the name of module from which the "root value"
  6. * was imported.
  7. */
  8. export default function resolveToModule(path) {
  9. if (path.isVariableDeclarator()) {
  10. if (path.node.init) {
  11. return resolveToModule(path.get('init'));
  12. }
  13. }
  14. else if (path.isCallExpression()) {
  15. const callee = path.get('callee');
  16. if (callee.isIdentifier({ name: 'require' })) {
  17. return path.node.arguments[0].value;
  18. }
  19. return resolveToModule(callee);
  20. }
  21. else if (path.isIdentifier() || path.isJSXIdentifier()) {
  22. const valuePath = resolveToValue(path);
  23. if (valuePath !== path) {
  24. return resolveToModule(valuePath);
  25. }
  26. if (path.parentPath.isObjectProperty()) {
  27. return resolveToModule(path.parentPath);
  28. }
  29. }
  30. else if (path.isObjectProperty() || path.isObjectPattern()) {
  31. return resolveToModule(path.parentPath);
  32. }
  33. else if (path.parentPath?.isImportDeclaration()) {
  34. return path.parentPath.node.source.value;
  35. }
  36. else if (path.isMemberExpression()) {
  37. path = getMemberExpressionRoot(path);
  38. return resolveToModule(path);
  39. }
  40. return null;
  41. }