-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
58 lines (50 loc) · 1.68 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const get = require('lodash/get');
// helper func which targets possible react components
const hasDeclaration = (singleNode, propTypeNode) => {
if (
!singleNode.type.match(
/[Function|Variable|Class|Export(Named|Default)]Declaration/
)
) {
return false;
}
const isDefaultOrNamedExport =
get(singleNode, 'declaration.id.name') === propTypeNode.name ||
get(singleNode, 'declaration.id.name.declarations[0].id.name') ===
propTypeNode.name;
if (isDefaultOrNamedExport) return true;
const isVariableOrFunctionStatement =
get(singleNode, 'id.name') === propTypeNode.name ||
get(singleNode, 'declaration[0].id.name') === propTypeNode.name;
if (isVariableOrFunctionStatement) return true;
return false;
};
module.exports = {
rules: {
'proptype-definition-above-fn': {
create(context) {
return {
AssignmentExpression(node) {
const propTypeNode = get(node, 'left.object');
const compareValue = get(propTypeNode, 'start');
const propName = get(node, 'left.property.name');
if (['propTypes', 'defaultProps'].includes(propName)) {
const body = get(node, 'parent.parent.body', []);
const targetNode = body.find(element =>
hasDeclaration(element, propTypeNode)
);
if (targetNode && targetNode.end < compareValue) {
return context.report(
node,
node.loc,
'PropTypes/defaultProps definitions should exist above component declaration.'
);
}
}
return null;
}
};
}
}
}
};