Introduction
Next.js has become a popular framework for React applications, offering server-side rendering, static site generation, and a great developer experience. However, as your project grows, maintaining consistent code style becomes increasingly important. This guide will help you set up a robust code formatting system using Prettier and ESLint in your Next.js projects.
By the end of this tutorial, you'll have a Next.js project with:
- Automated code formatting with Prettier
- Code quality checks with ESLint
- Editor integration for real-time feedback
- Pre-commit hooks to ensure code quality
Setting Up Your Next.js Project
First, let's create a new Next.js project if you don't have one already:
npx create-next-app@latest my-nextjs-app
cd my-nextjs-app
The latest version of Next.js comes with some ESLint configuration out of the box, but we'll enhance it for a more comprehensive setup.
Installing and Configuring ESLint
Next.js includes a basic ESLint configuration, but we'll extend it to work seamlessly with Prettier:
# Install additional ESLint packages
npm install --save-dev eslint-config-prettier eslint-plugin-prettier
Now, update your .eslintrc.json
file (create it
if it doesn't exist):
{
"extends": [
"next/core-web-vitals",
"prettier"
],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error",
"react/react-in-jsx-scope": "off",
"react/prop-types": "off",
"react/no-unescaped-entities": "warn",
"no-unused-vars": [
"warn",
{ "argsIgnorePattern": "^_", "varsIgnorePattern": "^_" }
]
}
}
This configuration:
- Extends Next.js's recommended rules
- Integrates Prettier as an ESLint plugin
- Disables React rules that aren't needed in Next.js
- Adds warnings for unused variables (with some exceptions)
Installing and Configuring Prettier
Now let's set up Prettier for code formatting:
# Install Prettier
npm install --save-dev prettier
# Create configuration files
echo {} > .prettierrc.json
echo "node_modules\\n.next\\nout\\nbuild\\n.vercel" > .prettierignore
Configure Prettier in .prettierrc.json
:
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100,
"bracketSpacing": true,
"arrowParens": "always",
"endOfLine": "lf",
"jsxSingleQuote": false,
"jsxBracketSameLine": false
}
This configuration sets up Prettier with common preferences for React/Next.js projects. Feel free to adjust these settings according to your team's preferences.
Adding NPM Scripts
Add these scripts to your package.json
for easy
formatting and linting:
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,css,md}\"",
"format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\""
}
Now you can run:
-
npm run lint
to check for ESLint issues -
npm run format
to format all files with Prettier -
npm run format:check
to check if files are properly formatted
VS Code Integration
For a seamless experience in VS Code, follow these steps:
- Install the ESLint and Prettier extensions
-
Create or update
.vscode/settings.json
:
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"prettier.requireConfig": true,
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
]
}
This configuration will:
- Format your code with Prettier when you save a file
- Apply ESLint fixes automatically on save
- Ensure Prettier only runs when a config file is present
Pre-commit Hooks with Husky
To ensure all committed code is properly formatted, let's set up pre-commit hooks with Husky and lint-staged:
# Install husky and lint-staged
npm install --save-dev husky lint-staged
# Initialize husky
npx husky install
npm set-script prepare "husky install"
npx husky add .husky/pre-commit "npx lint-staged"
Add this configuration to your package.json
:
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"*.{json,css,md}": [
"prettier --write"
]
}
Now, whenever you commit code, Husky will run lint-staged, which will:
- Run ESLint with auto-fix on JavaScript/TypeScript files
- Format all files with Prettier
This ensures that all code in your repository is consistently formatted.
Tailwind CSS Integration
If you're using Tailwind CSS with your Next.js project (which is common), you can add the Tailwind plugin for Prettier:
npm install --save-dev prettier-plugin-tailwindcss
Update your .prettierrc.json
:
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100,
"bracketSpacing": true,
"arrowParens": "always",
"endOfLine": "lf",
"jsxSingleQuote": false,
"plugins": ["prettier-plugin-tailwindcss"]
}
This plugin will automatically sort your Tailwind CSS classes according to the recommended class order, making your code more consistent and easier to read.
Troubleshooting Common Issues
Here are solutions to some common issues you might encounter:
ESLint and Prettier Conflicts
If you see conflicting rules between ESLint and Prettier, make sure:
-
You've added
"prettier"
to the{" "}extends
array in your ESLint config -
The
"prettier"
extension is the last one in the{" "}extends
array
Husky Not Running
If Husky isn't running your pre-commit hooks:
-
Make sure you've run
npx husky install
-
Check that the
.husky
directory exists in your project -
Ensure the pre-commit file has execute permissions (
chmod +x .husky/pre-commit
)
VS Code Not Formatting on Save
If VS Code isn't formatting on save:
- Check that you have the Prettier extension installed
-
Verify your
.vscode/settings.json
configuration - Make sure you don't have conflicting formatter extensions enabled
Conclusion
With this setup, your Next.js project will have consistent code formatting across your team. Prettier handles the formatting, ESLint catches potential issues, and pre-commit hooks ensure all committed code follows your standards.
This approach saves time on code reviews, reduces merge conflicts, and helps maintain a clean, consistent codebase. As your project grows, you'll appreciate having these tools in place to keep your code quality high.
Remember that code formatting is just one aspect of code quality. Consider also implementing:
- Unit and integration tests
- Type checking with TypeScript
- Accessibility checks
- Performance monitoring
These practices, combined with consistent formatting, will help you build high-quality Next.js applications.