index.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  7. var _path = require("path");
  8. var _core = require("@babel/core");
  9. var _default = (0, _helperPluginUtils.declare)(api => {
  10. api.assertVersion(7);
  11. function addDisplayName(id, call) {
  12. const props = call.arguments[0].properties;
  13. let safe = true;
  14. for (let i = 0; i < props.length; i++) {
  15. const prop = props[i];
  16. const key = _core.types.toComputedKey(prop);
  17. if (_core.types.isLiteral(key, {
  18. value: "displayName"
  19. })) {
  20. safe = false;
  21. break;
  22. }
  23. }
  24. if (safe) {
  25. props.unshift(_core.types.objectProperty(_core.types.identifier("displayName"), _core.types.stringLiteral(id)));
  26. }
  27. }
  28. const isCreateClassCallExpression = _core.types.buildMatchMemberExpression("React.createClass");
  29. const isCreateClassAddon = callee => callee.name === "createReactClass";
  30. function isCreateClass(node) {
  31. if (!node || !_core.types.isCallExpression(node)) return false;
  32. if (!isCreateClassCallExpression(node.callee) && !isCreateClassAddon(node.callee)) {
  33. return false;
  34. }
  35. const args = node.arguments;
  36. if (args.length !== 1) return false;
  37. const first = args[0];
  38. if (!_core.types.isObjectExpression(first)) return false;
  39. return true;
  40. }
  41. return {
  42. name: "transform-react-display-name",
  43. visitor: {
  44. ExportDefaultDeclaration({
  45. node
  46. }, state) {
  47. if (isCreateClass(node.declaration)) {
  48. const filename = state.filename || "unknown";
  49. let displayName = _path.basename(filename, _path.extname(filename));
  50. if (displayName === "index") {
  51. displayName = _path.basename(_path.dirname(filename));
  52. }
  53. addDisplayName(displayName, node.declaration);
  54. }
  55. },
  56. CallExpression(path) {
  57. const {
  58. node
  59. } = path;
  60. if (!isCreateClass(node)) return;
  61. let id;
  62. path.find(function (path) {
  63. if (path.isAssignmentExpression()) {
  64. id = path.node.left;
  65. } else if (path.isObjectProperty()) {
  66. id = path.node.key;
  67. } else if (path.isVariableDeclarator()) {
  68. id = path.node.id;
  69. } else if (path.isStatement()) {
  70. return true;
  71. }
  72. if (id) return true;
  73. });
  74. if (!id) return;
  75. if (_core.types.isMemberExpression(id)) {
  76. id = id.property;
  77. }
  78. if (_core.types.isIdentifier(id)) {
  79. addDisplayName(id.name, node);
  80. }
  81. }
  82. }
  83. };
  84. });
  85. exports.default = _default;