@zhigang1992/babel-plugin-react-anonymous-display-name
Version:
Automatically add displayName properties to your React project.
67 lines (52 loc) • 1.85 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
const SUPPORTED_HOCS = ['forwardRef', 'memo'];
const isAnonymousComponent = (t, callee, hocs) => {
if (t.isIdentifier(callee) && hocs.includes(callee.name)) {
return true;
}
if (t.isMemberExpression(callee)) {
const {
property
} = callee;
if (t.isIdentifier(property) && hocs.includes(property.name)) {
return true;
}
}
return false;
};
const isNamedAlready = (t, node) => {
if (t.isArrowFunctionExpression(node)) {
return false;
}
if (t.isFunctionExpression(node)) {
return Boolean(node.id);
}
return true;
};
var _default = ({
types: t
}) => ({
visitor: {
VariableDeclaration(path, state) {
var _state$opts$hocs;
const hocs = (_state$opts$hocs = state.opts.hocs) !== null && _state$opts$hocs !== void 0 ? _state$opts$hocs : SUPPORTED_HOCS;
const declarators = path.get('declarations');
declarators.forEach(declarator => {
if (!t.isIdentifier(declarator.node.id) || !t.isCallExpression(declarator.node.init)) {
return;
}
const firstArgument = declarator.node.init.arguments[0];
if (isNamedAlready(t, firstArgument) || !isAnonymousComponent(t, declarator.node.init.callee, hocs)) {
return;
}
declarator.replaceWith(t.variableDeclarator(t.identifier(declarator.node.id.name), t.callExpression(declarator.node.init.callee, [t.functionExpression(t.identifier(declarator.node.id.name), firstArgument.params, // is memo((props) => { return *; }) case
t.isBlockStatement(firstArgument.body) ? firstArgument.body : t.blockStatement([t.returnStatement(firstArgument.body)])), ...declarator.node.init.arguments.slice(1)])));
});
}
}
});
exports.default = _default;