Setting up code formatting and linting in your project is a great practice for maintaining consistency, readability, and catching potential errors early. For a Vite project, the most common tools are Prettier for formatting and ESLint for linting.
Here’s how to set them up:
1. Install Dependencies
First, you need to install Prettier and ESLint as development dependencies.
eslint-config-prettier: Turns off ESLint rules that may conflict with Prettier.
eslint-plugin-prettier: Runs Prettier as an ESLint rule and reports differences as ESLint issues.
For TypeScript Projects (in addition to the above):
bash
npm install --save-dev @typescript-eslint/eslint-plugin @typescript-eslint/parser prettier-plugin-tailwindcss # (if using TailwindCSS, otherwise omit)
# or
yarn add --dev @typescript-eslint/eslint-plugin @typescript-eslint/parser prettier-plugin-tailwindcss
# or
pnpm add --save-dev @typescript-eslint/eslint-plugin @typescript-eslint/parser prettier-plugin-tailwindcss
@typescript-eslint/eslint-plugin: ESLint rules for TypeScript.
@typescript-eslint/parser: The parser for TypeScript code.
prettier-plugin-tailwindcss: (Optional) If you are using Tailwind CSS, this plugin helps Prettier format Tailwind directives correctly.
2. Configure Prettier
Create a .prettierrc.js (or .prettierrc, .prettierrc.json, .prettierrc.yaml) file in your project's root directory. .js is recommended for flexibility.
.prettierrc.js:
js
/** @type {import('prettier').Config} */
module.exports = {
// Standard Prettier options
semi: true, // Add semicolons at the end of statements
trailingComma: 'all', // Add trailing commas where valid in ES5 (objects, arrays, etc.)
singleQuote: true, // Use single quotes instead of double quotes
printWidth: 100, // Specify the line length that the printer will wrap on
tabWidth: 2, // Specify the number of spaces per indentation-level
useTabs: false, // Indent lines with tabs instead of spaces
// If you are using Tailwind CSS, add this plugin
// plugins: ['prettier-plugin-tailwindcss'],
// Other useful options:
// arrowParens: 'always', // Include parentheses around a sole arrow function parameter
// bracketSameLine: false, // Put the closing bracket on the same line as the opening bracket
// quoteProps: 'as-needed', // Change when properties in objects are quoted
};
3. Configure ESLint
Create an .eslintrc.js file in your project's root directory.
For JavaScript Projects (.eslintrc.js):
js
module.exports = {
root: true, // Indicate that this is the root ESLint configuration
env: {
browser: true, // Enable browser global variables
es2021: true, // Enable ES2021 features
node: true, // Enable Node.js global variables
},
extends: [
'eslint:recommended', // Use ESLint's recommended rules
'plugin:prettier/recommended', // Use prettier for formatting and disable conflicting ESLint rules
],
parserOptions: {
ecmaVersion: 'latest', // Support the latest ECMAScript features
sourceType: 'module', // Allow using import/export syntax
},
// Add plugins if you need specific rule sets
plugins: ['prettier'],
rules: {
// You can add or override specific ESLint rules here
// For example, to allow console.log during development:
// 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
// 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
},
// Ignore certain files/directories
ignorePatterns: [
'vite.config.js', // Ignore Vite config file from linting
'.eslintrc.js', // Ignore ESLint config file itself
'dist/', // Ignore build output directory
'node_modules/', // Ignore Node modules directory
],
};
For TypeScript Projects (.eslintrc.js):
You'll need to extend the TypeScript ESLint recommended rules and specify the parser. Make sure you have a tsconfig.json file in your project root (you can create one with npx tsc --init).
js
module.exports = {
root: true,
env: {
browser: true,
es2021: true,
node: true,
},
plugins: [
'@typescript-eslint', // ESLint plugin for TypeScript
'prettier', // Run Prettier via ESLint
],
extends: [
'eslint:recommended', // Basic ESLint rules
'plugin:@typescript-eslint/recommended', // TypeScript-specific rules
// This line integrates Prettier: it enables the 'prettier' plugin
// and turns off all ESLint rules that might conflict with Prettier.
'plugin:prettier/recommended',
],
parser: '@typescript-eslint/parser', // Use the TypeScript parser
parserOptions: {
// Point ESLint to your tsconfig.json for type-aware linting
project: './tsconfig.json',
ecmaVersion: 'latest',
sourceType: 'module',
},
rules: {
// You can add or override specific ESLint/TypeScript rules here.
// For example, if you find Prettier causing issues with certain TS rules:
// '@typescript-eslint/indent': 'off', // Disables the ESLint indent rule that conflicts with Prettier
// Or add your own rules:
// '@typescript-eslint/explicit-function-return-type': 'warn', // Example: require return types for functions
},
// Ignore files that Vite uses or ESLint/Prettier shouldn't touch
ignorePatterns: [
'vite.config.js',
'.eslintrc.js',
'dist/',
'node_modules/',
'coverage/',
],
};
4. Add Scripts to package.json
Add these scripts to your package.json file to easily run ESLint and Prettier.
json
// package.json
{
// ... other configurations
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint src/**/*.{js,ts}", // Lint your source files
"lint:fix": "eslint --fix src/**/*.{js,ts}", // Fix automatically fixable linting issues
"format": "prettier --write src/**/*.{js,ts}" // Format all your source files with Prettier
}
// ...
}
Adjust the glob patterns (src/**/*.{js,ts}) if you have files in other directories or with different extensions (e.g., .vue, .jsx, .tsx).
5. Editor Integration (VS Code Example)
To get the best experience, configure your editor to format your code automatically on save.
Install Extensions:
ESLint: Search for dbaeumer.vscode-eslint in the VS Code Extensions marketplace and install it.
Prettier - Code formatter: Search for esbenp.prettier-vscode and install it.
Configure VS Code Settings:
Open your VS Code settings (File > Preferences > Settings or Ctrl+, / Cmd+,) and add the following:
json
{
"editor.formatOnSave": true,
// Specify Prettier as the default formatter for relevant languages
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
// Add other file types if needed
// "[vue]": {
// "editor.defaultFormatter": "esbenp.prettier-vscode"
// },
}
You can add these directly to your settings.json file (Ctrl+Shift+P or Cmd+Shift+P -> "Preferences: Open User Settings (JSON)").
6. Run Commands
To format your code:
bash
npm run format
To check for linting errors:
bash
npm run lint
To fix linting errors (and formatting):
bash
npm run lint:fix
With this setup, your code will be consistently formatted, and ESLint will help you catch common coding mistakes.