-
Notifications
You must be signed in to change notification settings - Fork 2
Code Quality Tools: ESLint & Prettier
Qianhe Chen edited this page Nov 9, 2024
·
1 revision
We use ESLint and Prettier to maintain code quality and consistency. ESLint helps catch bugs and enforce coding standards, while Prettier ensures consistent code formatting.
Feature | ESLint | Prettier |
---|---|---|
Purpose | Code quality rules & error detection | Code formatting |
Fixes | Logic, syntax, and style issues | Formatting only |
Configurability | Highly configurable rules | Limited formatting options |
Focus | Find problematic patterns | Make code pretty |
- Finds and fixes problems in your JavaScript/TypeScript code
- Enforces coding style
- Catches bugs before they run
- Ensures code quality
// .eslintrc.js
module.exports = {
root: true,
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'prettier' // Must be last
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
rules: {
'no-console': 'warn',
'no-unused-vars': 'error',
'@typescript-eslint/explicit-function-return-type': 'error'
}
}
// Bad code ESLint will catch
const unused = "I'm never used"; // no-unused-vars
console.log("debugging leftover"); // no-console
if (someVar == null) { } // eqeqeq
// Good code
const used = "I'm used";
logger.info("proper logging");
if (someVar === null) { }
- Formats code automatically
- Ensures consistent style
- Ends style debates
- Works with many file types
// .prettierrc
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2
}
// Before Prettier
const messy_code = "very messy" ;
function longFunction(a, b,c){
return a+b+c}
// After Prettier
const messy_code = 'very messy';
function longFunction(a, b, c) {
return a + b + c;
}
// .eslintrc.js
module.exports = {
extends: [
'eslint:recommended',
'prettier' // Prettier must be last
],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'error'
}
}
// settings.json
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,ts,tsx}": [
"eslint --fix",
"prettier --write"
]
}
}
# Install
pnpm add -D eslint prettier @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-config-prettier
# Check issues
pnpm eslint .
pnpm prettier --check .
# Fix issues
pnpm eslint --fix .
pnpm prettier --write .
For detailed configuration options and rules: