ArnaudBarre / eslint-plugin-react-refresh

Validate that your components can safely be updated with Fast Refresh
MIT License
206 stars 13 forks source link

False positive for negative number with allowConstantExport #43

Closed RandScullard closed 3 months ago

RandScullard commented 3 months ago

My eslintrc.cjs contains:

  rules: {
    "react-refresh/only-export-components": [
      "error",
      { "allowConstantExport": true },
    ],

I have a .tsx file with the following exported constant:

export const allTestCategories = -1

ESLint produces this error:

ERROR(ESLint) Fast refresh only works when a file only exports components. Use a new file to share constants or functions between components. (react-refresh/only-export-components)

If I simply change the constant value from -1 to 1, the ESLint error goes away. Looking at only-export-components.ts line 105, I see that you are checking for Literal, TemplateLiteral, and BinaryExpression, but the problem is that -1 is a UnaryExpression. I think you need to add UnaryExpression to your logic.

I tried this as a workaround:

export const allTestCategories = -1 as number

This produced a TSAsExpression, which is also not handled by your logic. I'm not sure of all the implications, but it might make sense to allow this as well.

ArnaudBarre commented 3 months ago

Thanks for investigating and debugging this! This is definitely a edge case I didn't though of.

The fix is published in 0.4.8

I choose to not include TSAsExpression, it would require some extra checks on the expression being cast and I don't see any reason why you will need a type assertion for something that should be a primitive value.