isDestructuredFromPragmaImport.js 2.6 KB

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