Skip to content

Commit 13806f1

Browse files
committed
Add support for variable reference to sort-prop-types (fixes #622)
1 parent 682ae68 commit 13806f1

File tree

2 files changed

+57
-5
lines changed

2 files changed

+57
-5
lines changed

lib/rules/sort-prop-types.js

+30-5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33
*/
44
'use strict';
55

6+
var find = require('array.prototype.find');
7+
8+
var variableUtil = require('../util/variable');
9+
610
// ------------------------------------------------------------------------------
711
// Rule Definition
812
// ------------------------------------------------------------------------------
@@ -150,11 +154,32 @@ module.exports = {
150154
},
151155

152156
MemberExpression: function(node) {
153-
if (isPropTypesDeclaration(node.property)) {
154-
var right = node.parent.right;
155-
if (right && right.type === 'ObjectExpression') {
156-
checkSorted(right.properties);
157-
}
157+
if (!isPropTypesDeclaration(node.property)) {
158+
return;
159+
}
160+
var right = node.parent.right;
161+
var declarations;
162+
switch (right && right.type) {
163+
case 'ObjectExpression':
164+
declarations = right.properties;
165+
break;
166+
case 'Identifier':
167+
var variable = find(variableUtil.variablesInScope(context), function (item) {
168+
return item.name === right.name;
169+
});
170+
if (
171+
!variable || !variable.defs[0] ||
172+
!variable.defs[0].node.init || !variable.defs[0].node.init.properties
173+
) {
174+
break;
175+
}
176+
declarations = variable.defs[0].node.init.properties;
177+
break;
178+
default:
179+
break;
180+
}
181+
if (declarations) {
182+
checkSorted(declarations);
158183
}
159184
},
160185

tests/lib/rules/sort-prop-types.js

+27
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,15 @@ ruleTester.run('sort-prop-types', rule, {
323323
'}'
324324
].join('\n'),
325325
parser: 'babel-eslint'
326+
}, {
327+
code: [
328+
'const propTypes = require(\'./externalPropTypes\')',
329+
'const TextFieldLabel = (props) => {',
330+
' return <div />;',
331+
'};',
332+
'TextFieldLabel.propTypes = propTypes;'
333+
].join('\n'),
334+
parserOptions: parserOptions
326335
}],
327336

328337
invalid: [{
@@ -624,5 +633,23 @@ ruleTester.run('sort-prop-types', rule, {
624633
column: 5,
625634
type: 'Property'
626635
}]
636+
}, {
637+
code: [
638+
'const propTypes = {',
639+
' b: PropTypes.string,',
640+
' a: PropTypes.string,',
641+
'};',
642+
'const TextFieldLabel = (props) => {',
643+
' return <div />;',
644+
'};',
645+
'TextFieldLabel.propTypes = propTypes;'
646+
].join('\n'),
647+
parserOptions: parserOptions,
648+
errors: [{
649+
message: ERROR_MESSAGE,
650+
line: 3,
651+
column: 3,
652+
type: 'Property'
653+
}]
627654
}]
628655
});

0 commit comments

Comments
 (0)