Eslint-plugin-react: sort-prop-types fix to account for comments

Created on 16 Aug 2018  ·  10Comments  ·  Source: yannickcr/eslint-plugin-react

I know comments on prop types are not in favour here, but for those who do have them, would it be acceptable to support sorting comments together with their prop types? i.e. currently the rule would fix

{
  /** z */
  z: PropTypes.string,
  /** a */
  a: PropTypes.any
}

to

propTypes: {
  /** z */
  a: PropTypes.any,
  /** a */
  z: PropTypes.string
}

Most helpful comment

comments: “above” | “below”

All 10 comments

How would you determine whether comments attach to the thing before, or the thing after?

Hmm... can you give an example where the comment goes after the thing you're commenting on? I'm having a difficulty coming up with a real use case.
AST-wise, there is a leadingComments property on the node that contains the comment before the node.

propTypes: {
  baz: PropTypes.any,
  foo: PropTypes.any,
  // ^ this is a foo, but the others don't need explanation
  bar: PropTypes.any,
}

Ok. Haven't really seen code like that. But if it's something people would do in your experience (as opposed to putting this is a foo above the foo), then yeah.

However, I’d say the current behavior is a bug, so your plan is probably a strict improvement.

Perhaps a plugin setting, that defaults to “above”, that determines comment attachment?

comments: “above” | “below”

(At plugin level tho, not rule)

Why? Are there other rules that would use it?

Any rule that moves code around :-) I’ve found over time that many rule configs belong instead as settings, and it’s easier to plan ahead.

I'm able to use sourceCode.getCommentsBefore(node) to process comments when attachment is "above". But finding this tricky to implement for the "below" attachment.

propTypes: {
  foo: PropTypes.any,
  // ^ this is a foo, but the others don't need explanation
  bar: PropTypes.any
}

If node is the entire foo property, then the comment will not be available in sourceCode.getCommentsAfter(node) because it's after the comma. So I need to either get down to the token level functions, or try using getCommentsBefore on the property that goes next (in this case, bar).

Also, here

propTypes: {
  foo: PropTypes.any, // <- this is a foo, but the others don't need explanation
  bar: PropTypes.any
}

the comment needs to be attached to foo as well (whether "above" or "below"), but it only differs from the previous example in a new line I think.
I'll continue working on this and see if I can make it work. We could use this rule internally.

Was this page helpful?
0 / 5 - 0 ratings