From 13806f1bc99817c06223a2b799bdc1125d208290 Mon Sep 17 00:00:00 2001 From: Yannick Croissant Date: Sat, 7 Jan 2017 20:49:41 +0000 Subject: [PATCH] Add support for variable reference to sort-prop-types (fixes #622) --- lib/rules/sort-prop-types.js | 35 +++++++++++++++++++++++++----- tests/lib/rules/sort-prop-types.js | 27 +++++++++++++++++++++++ 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/lib/rules/sort-prop-types.js b/lib/rules/sort-prop-types.js index b3c04f5482..817e4123d7 100644 --- a/lib/rules/sort-prop-types.js +++ b/lib/rules/sort-prop-types.js @@ -3,6 +3,10 @@ */ 'use strict'; +var find = require('array.prototype.find'); + +var variableUtil = require('../util/variable'); + // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ @@ -150,11 +154,32 @@ module.exports = { }, MemberExpression: function(node) { - if (isPropTypesDeclaration(node.property)) { - var right = node.parent.right; - if (right && right.type === 'ObjectExpression') { - checkSorted(right.properties); - } + if (!isPropTypesDeclaration(node.property)) { + return; + } + var right = node.parent.right; + var declarations; + switch (right && right.type) { + case 'ObjectExpression': + declarations = right.properties; + break; + case 'Identifier': + var variable = find(variableUtil.variablesInScope(context), function (item) { + return item.name === right.name; + }); + if ( + !variable || !variable.defs[0] || + !variable.defs[0].node.init || !variable.defs[0].node.init.properties + ) { + break; + } + declarations = variable.defs[0].node.init.properties; + break; + default: + break; + } + if (declarations) { + checkSorted(declarations); } }, diff --git a/tests/lib/rules/sort-prop-types.js b/tests/lib/rules/sort-prop-types.js index d18b8aa144..fd1fe835ba 100644 --- a/tests/lib/rules/sort-prop-types.js +++ b/tests/lib/rules/sort-prop-types.js @@ -323,6 +323,15 @@ ruleTester.run('sort-prop-types', rule, { '}' ].join('\n'), parser: 'babel-eslint' + }, { + code: [ + 'const propTypes = require(\'./externalPropTypes\')', + 'const TextFieldLabel = (props) => {', + ' return
;', + '};', + 'TextFieldLabel.propTypes = propTypes;' + ].join('\n'), + parserOptions: parserOptions }], invalid: [{ @@ -624,5 +633,23 @@ ruleTester.run('sort-prop-types', rule, { column: 5, type: 'Property' }] + }, { + code: [ + 'const propTypes = {', + ' b: PropTypes.string,', + ' a: PropTypes.string,', + '};', + 'const TextFieldLabel = (props) => {', + ' return
;', + '};', + 'TextFieldLabel.propTypes = propTypes;' + ].join('\n'), + parserOptions: parserOptions, + errors: [{ + message: ERROR_MESSAGE, + line: 3, + column: 3, + type: 'Property' + }] }] });