Set up automatic code formatting and linting in Visual Studio Code for consistent code quality across your team.
Things You'll Need
- Visual Studio Code installed
- Node.js project with package.json
- Basic understanding of npm
Steps
Follow these 8 steps to complete this guide
Install VS Code Extensions
Install the ESLint and Prettier extensions from the VS Code marketplace.
1. Open VS Code
2. Press Ctrl+Shift+X (Cmd+Shift+X on Mac)
3. Search for "ESLint" and install
4. Search for "Prettier - Code formatter" and install
5. Reload VS Code Install ESLint and Prettier Packages
Add ESLint and Prettier as dev dependencies to your project.
# Install ESLint and Prettier
npm install -D eslint prettier
# Install integration packages
npm install -D eslint-config-prettier eslint-plugin-prettier Tips
- eslint-config-prettier disables ESLint rules that conflict with Prettier
- eslint-plugin-prettier runs Prettier as an ESLint rule
Initialize ESLint Configuration
Create an ESLint configuration file for your project.
# Initialize ESLint (interactive)
npx eslint --init
# Or create .eslintrc.json manually Configure ESLint
Set up your .eslintrc.json with appropriate rules and Prettier integration.
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:prettier/recommended"
],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {
"prettier/prettier": "error",
"no-console": "warn",
"no-unused-vars": "warn"
}
} Create Prettier Configuration
Create a .prettierrc file to define your code formatting preferences.
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 80,
"arrowParens": "avoid"
} Tips
- Adjust these rules to match your team's preferences
- The configuration will be shared with all team members
Configure VS Code Settings
Update your VS Code settings to format on save and use ESLint for fixing.
// .vscode/settings.json
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
]
} Add npm Scripts
Add convenient scripts to your package.json for linting and formatting.
{
"scripts": {
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"format": "prettier --write "**/*.{js,jsx,ts,tsx,json,css,md}""
}
} Tips
- Run 'npm run lint:fix' before committing code
- Consider adding these to a pre-commit hook
Test Your Setup
Create a test file with formatting issues and save it to verify auto-formatting works.
// test.js - Deliberately messy
const test={a:1,b:2}
function hello( ){
console.log("hello")
}
// After save, should be formatted to:
const test = { a: 1, b: 2 };
function hello() {
console.log('hello');
} Was this guide helpful?
Check out more step-by-step guides for development, deployment, debugging, and configuration.