Skip to content

Rule proposal: Prevent stray syntax from ending up in front of users #3586

Open

Description

JSX syntax makes it very easy to leave stray syntax behind while updating code. For example, say you have:

return <h1>Hello!</h1>;

And then realize you want to wrap it in some other element. You might accidentally end up with:

return (
  <Wrapper>
    <h1>Hello!</h1>;
  </Wrapper>
);

Which will leave a stray semicolon in your user-facing UI.


Does a rule already exist here, or elsewhere, to prevent that type of bug?

If not, I wrote one which looks like this:

const SUSPECT_STRINGS = new Set([';', '}', ')}', ');']);

module.exports = {
  create(context) {
    return {
      'JSXText, Literal'(node) {
        if (
          (node.type !== 'JSXText' && node._babelType !== 'JSXText') ||
          typeof node.value !== 'string'
        ) {
          return;
        }
        if (!SUSPECT_STRINGS.has(node.value.trim())) {
          return;
        }
        context.report({node, message: 'Possible JSX Cruft'});
      },
    };
  },
};

Which uncovered hundreds of issues in our large code base with relatively few false positives.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions