ESLint (ESLint (ECMAScript Lint) is a static code analysis tool used to identify and fix problems in JavaScript code. It helps enforce coding styles, detect potential errors, and maintain code consistency across projects.
- Detects syntax errors and bugs early.
- Enforces best coding practices.
- Improves code readability and maintainability.
- Standardizes code across teams.
- Integrates with CI/CD pipelines.
From ESLint v9.0.0, .eslintrc.*
is no longer the default configuration file. The new standard is eslint.config.js
.
Run the following command in your React project:
npm install --save-dev eslint @eslint/js eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y
Since ESLint v9+ does not support .eslintrc.*
, create a new eslint.config.js
file:
// eslint.config.js (Flat Config Format)
const js = require("@eslint/js");
const react = require("eslint-plugin-react");
const reactHooks = require("eslint-plugin-react-hooks");
const jsxA11y = require("eslint-plugin-jsx-a11y");
module.exports = [
js.configs.recommended,
{
files: ["**/*.{js,jsx,ts,tsx}"],
plugins: {
react,
"react-hooks": reactHooks,
"jsx-a11y": jsxA11y
},
languageOptions: {
ecmaVersion: "latest",
sourceType: "module",
parserOptions: {
ecmaFeatures: {
jsx: true
}
}
},
settings: {
react: {
version: "detect"
}
},
rules: {
// Extend recommended rules from plugins
...react.configs.recommended.rules,
...reactHooks.configs.recommended.rules,
...jsxA11y.configs.recommended.rules,
// React specific rules
"react/prop-types": "off", // Disable prop-types as we may use TypeScript
"react/react-in-jsx-scope": "off", // Not needed in React 17+
// Accessibility rules
"jsx-a11y/anchor-is-valid": "warn", // Ensure anchor tags have valid href
// Code style rules
"quotes": ["error", "double"], // Enforce double quotes
"semi": ["error", "always"] // Require semicolons
}
}
];
To ensure ESLint only checks the src
directory and its subdirectories, add the following script to package.json
:
"scripts": {
"lint": "eslint src",
"lint:fix": "eslint src --fix"
}
Now, you can run:
npm run lint # To check for lint errors
npm run lint:fix # To automatically fix lint errors
For better linting support, install the ESLint extension in VS Code.
Enable Auto Fix on Save by adding this to settings.json
:
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
By following these steps, your React project will have a fully configured ESLint v9+ setup, ensuring code consistency, error detection, and best practices. Let me know if you need any modifications!