87

In .tsx file, why does eslint report:

JSX not allowed in files with extension '.tsx'eslint(react/jsx-filename-extension)

How can I update the eslint config can resolve this message:

enter image description here

Dave Mackey
  • 4,306
  • 21
  • 78
  • 136
Baochang Li
  • 891
  • 1
  • 6
  • 7
  • Why does your eslint check typescript files, in the first place? AFAIK it won't do it unless explicitly told so. – Cerberus Apr 11 '19 at 04:21
  • try this one: https://stackoverflow.com/questions/43031126/jsx-not-allowed-in-files-with-extension-js-with-eslint-config-airbnb – Elad Apr 11 '19 at 13:20

2 Answers2

123

You probably want to configure the react/jsx-filename-extension rule in your .eslintrc.js so that ESLint is happy about JSX inside your TypeScript files:

rules:  {
  'react/jsx-filename-extension': [2, { 'extensions': ['.js', '.jsx', '.ts', '.tsx'] }],
},
dmudro
  • 2,894
  • 1
  • 21
  • 23
  • 4
    Why is this necessary exactly? I see it here as well: https://www.npmjs.com/package/tslint-config-airbnb. Isn't .tsx an obvious filename extension? – Remi Nov 25 '19 at 20:09
  • Good point. It's obvious from a TypeScript perspective but they haven't included `.tsx` in default values. – dmudro Nov 26 '19 at 13:40
  • 5
    I believe the first parameter which is `2` refers to a boolean `additionalProperties `and should be `1` (not that it matters here). See: https://github.com/yannickcr/eslint-plugin-react/blob/master/lib/rules/jsx-filename-extension.js and other solutions https://stackoverflow.com/a/43031230/1800854 – Mo Beigi Jun 21 '20 at 06:08
  • 2
    @MoBeigi: No, `1` means `warning`, `2` means `error`. Both are valid. – NeoZoom.lua Mar 24 '22 at 23:10
  • 2
    @Remi if you are using airbnb, you need a separate package for typescript support at the moment: https://www.npmjs.com/package/eslint-config-airbnb-typescript It allows JSX in .tsx files. – Nacho H Jan 24 '23 at 00:35
  • @NachoH I installed eslint-config-airbnb-typescript and then added the following line to my `.eslintrc` file: `"extends": ["airbnb-typescript", "prettier"],` but when I run `npm run lint` it says Error: Error while loading rule '@typescript-eslint/dot-notation': You have used a rule which requires parserServices to be generated.: – Will Jun 07 '23 at 13:52
46

Add this rule under the rules section of your eslint configuration:

"rules": {
  "react/jsx-filename-extension": [1, { "extensions": [".tsx", ".ts"] }]
}
Wachaga Mwaura
  • 3,310
  • 3
  • 28
  • 31