isDestructuredFromPragmaImport.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. const pragmaUtil = require('./pragma');
  3. const variableUtil = require('./variable');
  4. /**
  5. * Check if variable is destructured from pragma import
  6. *
  7. * @param {string} variable The variable name to check
  8. * @param {Context} context eslint context
  9. * @returns {Boolean} True if createElement is destructured from the pragma
  10. */
  11. module.exports = function isDestructuredFromPragmaImport(variable, context) {
  12. const pragma = pragmaUtil.getFromContext(context);
  13. const variables = variableUtil.variablesInScope(context);
  14. const variableInScope = variableUtil.getVariable(variables, variable);
  15. if (variableInScope) {
  16. const latestDef = variableUtil.getLatestVariableDefinition(variableInScope);
  17. if (latestDef) {
  18. // check if latest definition is a variable declaration: 'variable = value'
  19. if (latestDef.node.type === 'VariableDeclarator' && latestDef.node.init) {
  20. // check for: 'variable = pragma.variable'
  21. if (
  22. latestDef.node.init.type === 'MemberExpression'
  23. && latestDef.node.init.object.type === 'Identifier'
  24. && latestDef.node.init.object.name === pragma
  25. ) {
  26. return true;
  27. }
  28. // check for: '{variable} = pragma'
  29. if (
  30. latestDef.node.init.type === 'Identifier'
  31. && latestDef.node.init.name === pragma
  32. ) {
  33. return true;
  34. }
  35. // "require('react')"
  36. let requireExpression = null;
  37. // get "require('react')" from: "{variable} = require('react')"
  38. if (latestDef.node.init.type === 'CallExpression') {
  39. requireExpression = latestDef.node.init;
  40. }
  41. // get "require('react')" from: "variable = require('react').variable"
  42. if (
  43. !requireExpression
  44. && latestDef.node.init.type === 'MemberExpression'
  45. && latestDef.node.init.object.type === 'CallExpression'
  46. ) {
  47. requireExpression = latestDef.node.init.object;
  48. }
  49. // check proper require.
  50. if (
  51. requireExpression
  52. && requireExpression.callee
  53. && requireExpression.callee.name === 'require'
  54. && requireExpression.arguments[0]
  55. && requireExpression.arguments[0].value === pragma.toLocaleLowerCase()
  56. ) {
  57. return true;
  58. }
  59. return false;
  60. }
  61. // latest definition is an import declaration: import {<variable>} from 'react'
  62. if (
  63. latestDef.parent
  64. && latestDef.parent.type === 'ImportDeclaration'
  65. && latestDef.parent.source.value === pragma.toLocaleLowerCase()
  66. ) {
  67. return true;
  68. }
  69. }
  70. }
  71. return false;
  72. };