Fixing ESLint Parsing Errors in JSX Files
The “Unexpected token <” error occurs when ESLint encounters JSX syntax but isn’t properly configured to handle it. Here’s how to resolve this issue:
Solution 1: Configure ESLint for React
1. Install Required ESLint Packages
npm install --save-dev eslint-plugin-react eslint-plugin-react-hooks @babel/eslint-parser
2. Update ESLint Configuration (.eslintrc.js or .eslintrc.json)
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
],
parser: '@babel/eslint-parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
requireConfigFile: false,
babelOptions: {
presets: ['@babel/preset-react'],
},
},
plugins: ['react', 'react-hooks'],
rules: {
// Add any custom rules here
},
settings: {
react: {
version: 'detect',
},
},
};
Solution 2: Quick Fix for Create React App
If using Create React App, ESLint is preconfigured. Just ensure:
- Your file has a
.jsx
extension for JSX files - Or add this to
package.json
:
"eslintConfig": {
"extends": "react-app"
}
Solution 3: Using TypeScript (TSX)
For TypeScript projects:
- Install additional dependencies:
npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin
- Update ESLint config:
module.exports = {
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:react/recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: {
project: './tsconfig.json',
ecmaFeatures: {
jsx: true,
},
},
// ... rest of config
};
Common Mistakes to Avoid
- Missing file extensions:
- Use
.jsx
for JSX files - Use
.tsx
for TypeScript + JSX files
- Incorrect parser configuration:
- Ensure you’re using either
@babel/eslint-parser
or@typescript-eslint/parser
- Outdated React version specification:
settings: {
react: {
version: 'detect', // Automatically detects React version
},
},
Additional Configuration Options
For advanced setups, you might need:
- JSX-specific rules:
rules: {
'react/jsx-uses-react': 'error',
'react/jsx-uses-vars': 'error',
'react/react-in-jsx-scope': 'off', // Not needed for React 17+
}
- Airbnb style guide (popular alternative):
npm install --save-dev eslint-config-airbnb
Then extend it:
extends: [
'airbnb',
'airbnb/hooks',
'plugin:react/recommended',
],
Verifying Your Setup
- Create a test component (
Test.jsx
):
import React from 'react';
function Test() {
return <div>Test Component</div>;
}
export default Test;
- Run ESLint:
npx eslint Test.jsx
If no errors appear, your configuration is working correctly. If errors persist, check:
- File extensions
- Parser configuration
- Installed package versions