- Understanding Prettier
- Setting Up Prettier
- Integrating Prettier into Your Workflow
- Customizing Prettier
- Handling Common Issues
- Real-World Examples
- Automating Prettier in Development Workflows
- Advanced Prettier Usage
- Future Trends in Code Formatting
- Best Practices for Using Prettier
- Conclusion
Ensuring consistent code formatting is essential for maintaining readability and quality in software projects. Prettier is a powerful tool that automatically formats your code, helping you achieve uniform style across your codebase. In this article, we’ll explore how to use Prettier to ensure consistent code formatting, its benefits, and how to integrate it into your development workflow.
Understanding Prettier

What is Prettier?
Prettier is an opinionated code formatter that supports multiple programming languages. It enforces a consistent style by parsing your code and re-printing it with its own set of formatting rules.
Prettier removes the need for manual formatting and helps avoid debates about code style among team members, making your codebase cleaner and more maintainable.
Why Use Prettier?
Using Prettier ensures that all code adheres to a uniform style, making it easier to read and understand. This consistency helps reduce cognitive load, allowing developers to focus on the logic rather than formatting issues. Prettier also saves time by automating the formatting process, eliminating the need for manual adjustments and reducing the risk of formatting errors.
Setting Up Prettier
Installing Prettier
To start using Prettier, you need to install it in your project. If you’re using npm, you can install Prettier as a development dependency by running:
npm install --save-dev prettier
If you’re using Yarn, you can install it with:
yarn add --dev prettier
Once installed, you can format your code by running Prettier from the command line.
Creating a Configuration File
Prettier allows you to customize its behavior using a configuration file. You can create a .prettierrc
file in the root of your project to specify your preferred settings. For example, to use single quotes and set the tab width to 2 spaces, your configuration file might look like this:
{
"singleQuote": true,
"tabWidth": 2
}
You can also use other formats for the configuration file, such as .prettierrc.yaml
, .prettierrc.toml
, or even specify settings directly in package.json
.
Ignoring Files
If there are files or directories you want Prettier to ignore, you can create a .prettierignore
file. This file works similarly to .gitignore
, allowing you to specify patterns for files and directories that Prettier should skip. For example:
node_modules
dist
This tells Prettier to ignore the node_modules
and dist
directories.
Integrating Prettier into Your Workflow

Using Prettier with Your Code Editor
Many popular code editors have plugins that integrate Prettier, allowing you to format code automatically on save. For example, if you’re using Visual Studio Code, you can install the Prettier – Code formatter extension from the marketplace. Once installed, you can configure the extension to format code on save by adding the following setting to your settings.json
file:
{
"editor.formatOnSave": true
}
This ensures that every time you save a file, Prettier automatically formats it according to your configuration.
Using Prettier with Git Hooks
To ensure that all code committed to your repository is formatted consistently, you can use Git hooks. Tools like Husky and lint-staged make it easy to set up pre-commit hooks that run Prettier before changes are committed. First, install Husky and lint-staged:
npm install --save-dev husky lint-staged
Then, add the following configuration to your package.json
:
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.js": "prettier --write"
}
}
This configuration tells Husky to run lint-staged before each commit, and lint-staged will use Prettier to format all JavaScript files.
Running Prettier in Your CI Pipeline
Integrating Prettier into your Continuous Integration (CI) pipeline ensures that your code remains consistently formatted even when contributions come from different developers. You can add a step to your CI configuration to run Prettier and check for formatting issues. For example, in a GitHub Actions workflow, you might add:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install dependencies
run: npm install
- name: Run Prettier
run: npx prettier --check .
This workflow installs dependencies and runs Prettier to check if the code is properly formatted. If any files are not formatted correctly, the job will fail, prompting the developer to fix the formatting issues.
Customizing Prettier
Configuring Options
Prettier comes with a set of default options, but you can customize it to fit your project’s needs. The configuration file allows you to tweak various settings such as line width, trailing commas, and bracket spacing. Here are some of the common options you can customize:
- printWidth: Specifies the line length that Prettier will wrap on. The default is 80 characters.
- tabWidth: Sets the number of spaces per indentation level. The default is 2.
- useTabs: If set to
true
, Prettier will use tabs for indentation instead of spaces. - semi: If set to
true
, Prettier will add a semicolon at the end of every statement. - singleQuote: If set to
true
, Prettier will use single quotes instead of double quotes. - trailingComma: Controls the printing of trailing commas wherever possible. Options are
"none"
,"es5"
, and"all"
. - bracketSpacing: If set to
true
, Prettier will add spaces inside object literals.
An example .prettierrc
file with customized settings might look like this:
{
"printWidth": 100,
"tabWidth": 4,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": true
}
Extending Prettier Configuration
Sometimes, you might want to extend Prettier’s configuration to enforce additional rules or combine it with other tools like ESLint. You can achieve this by using prettier-eslint
, a tool that formats your code using Prettier followed by ESLint. First, install prettier-eslint
:
npm install --save-dev prettier-eslint
Then, you can create a script in your package.json
to run prettier-eslint
:
{
"scripts": {
"format": "prettier-eslint --write '**/*.js'"
}
}
This script will format all JavaScript files in your project using both Prettier and ESLint, ensuring that your code adheres to the rules specified in both tools.
Handling Common Issues

Resolving Conflicts with ESLint
When using Prettier and ESLint together, you might encounter conflicts where both tools have overlapping rules. To resolve these conflicts, you can use eslint-config-prettier
, a configuration that disables ESLint rules that might conflict with Prettier. First, install the configuration:
npm install --save-dev eslint-config-prettier
Then, extend your ESLint configuration to include eslint-config-prettier
:
{
"extends": ["eslint:recommended", "plugin:react/recommended", "prettier"],
"rules": {
// Your custom rules
}
}
This setup ensures that Prettier and ESLint work together seamlessly without conflicting rules.
Dealing with Large Codebases
In large codebases, formatting all files at once with Prettier can be overwhelming and may introduce numerous changes. To handle this, you can gradually apply Prettier to your codebase. Start by formatting new and modified files only. You can enforce this by integrating Prettier with your version control system using pre-commit hooks, as discussed earlier.
Additionally, you can use tools like eslint-plugin-prettier
to enforce Prettier’s formatting rules within ESLint. This ensures that any new code adheres to the formatting rules, while you gradually format the rest of the codebase.
Real-World Examples
Example 1: Setting Up Prettier in a React Project
Let’s walk through setting up Prettier in a React project. First, install Prettier and the necessary dependencies:
npm install --save-dev prettier eslint eslint-config-prettier eslint-plugin-prettier
Create a .prettierrc
file in the root of your project:
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 2
}
Next, configure ESLint to work with Prettier by creating an .eslintrc.json
file:
{
"extends": ["react-app", "plugin:prettier/recommended"],
"rules": {
"prettier/prettier": [
"error",
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 2
}
]
}
}
This setup ensures that your React project’s code is consistently formatted according to Prettier’s rules, with ESLint enforcing the same rules.
Example 2: Integrating Prettier with a Node.js Project
For a Node.js project, the process is similar. First, install Prettier and any necessary dependencies:
npm install --save-dev prettier eslint eslint-config-prettier eslint-plugin-prettier
Create a .prettierrc
file:
{
"semi": false,
"singleQuote": true,
"trailingComma": "none"
}
Then, configure ESLint to work with Prettier by creating an .eslintrc.json
file:
{
"extends": ["eslint:recommended", "plugin:prettier/recommended"],
"rules": {
"prettier/prettier": [
"error",
{
"semi": false,
"singleQuote": true,
"trailingComma": "none"
}
]
}
}
This configuration ensures that your Node.js project’s code is formatted consistently, with both Prettier and ESLint enforcing the same rules.
Automating Prettier in Development Workflows

Integrating Prettier with Build Tools
Integrating Prettier with build tools like Webpack, Gulp, or Grunt can help automate the formatting process further. This ensures that your code is consistently formatted as part of your build process, reducing the need for manual intervention.
Using Prettier with Webpack
To integrate Prettier with Webpack, you can use the prettier-webpack-plugin
. First, install the plugin:
npm install --save-dev prettier-webpack-plugin
Then, configure the plugin in your webpack.config.js
file:
const PrettierPlugin = require('prettier-webpack-plugin');
module.exports = {
// Other Webpack configurations
plugins: [
new PrettierPlugin({
singleQuote: true,
trailingComma: 'all',
printWidth: 80,
tabWidth: 2
})
]
};
This setup ensures that Prettier runs every time you build your project with Webpack.
Using Prettier with Gulp
To use Prettier with Gulp, you can leverage the gulp-prettier
plugin. First, install the plugin:
npm install --save-dev gulp gulp-prettier
Then, create a gulpfile.js
with the following content:
const gulp = require('gulp');
const prettier = require('gulp-prettier');
gulp.task('format', () => {
return gulp
.src('src/**/*.js')
.pipe(prettier({ singleQuote: true, trailingComma: 'all', printWidth: 80, tabWidth: 2 }))
.pipe(gulp.dest('src'));
});
Run the format
task to format your code with Prettier using Gulp.
Using Prettier with Grunt
To integrate Prettier with Grunt, you can use the grunt-prettier
plugin. First, install the plugin:
npm install --save-dev grunt grunt-prettier
Then, configure the plugin in your Gruntfile.js
:
module.exports = function (grunt) {
grunt.initConfig({
prettier: {
options: {
singleQuote: true,
trailingComma: 'all',
printWidth: 80,
tabWidth: 2
},
files: {
src: ['src/**/*.js']
}
}
});
grunt.loadNpmTasks('grunt-prettier');
grunt.registerTask('default', ['prettier']);
};
This configuration ensures that Prettier formats your code when you run the default Grunt task.
Advanced Prettier Usage
Using Prettier with Preprocessors
Prettier supports various preprocessors like TypeScript, JSX, and CSS-in-JS. This means you can use Prettier to format your entire codebase, regardless of the technologies you are using.
Prettier with TypeScript
To format TypeScript code, ensure you have installed Prettier and the necessary TypeScript support:
npm install --save-dev prettier @typescript-eslint/parser @typescript-eslint/eslint-plugin
Create or update your .prettierrc
file with your desired settings, and ensure your ESLint configuration is set up to support TypeScript:
{
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"extends": ["plugin:@typescript-eslint/recommended", "plugin:prettier/recommended"],
"rules": {
"prettier/prettier": [
"error",
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 2
}
]
}
}
Prettier with JSX and React
To use Prettier with JSX and React, ensure your Prettier configuration supports JSX formatting:
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 2,
"jsxSingleQuote": true
}
This configuration ensures that Prettier formats your React components correctly.
Combining Prettier with Other Tools
Combining Prettier with other tools like stylelint for CSS or Markdownlint for Markdown files can ensure consistency across your entire project.
Prettier with stylelint
To use Prettier with stylelint, you can install stylelint-prettier
and stylelint-config-prettier
:
npm install --save-dev stylelint stylelint-prettier stylelint-config-prettier
Configure stylelint to use Prettier in your stylelint.config.js
:
module.exports = {
extends: [
'stylelint-config-standard',
'stylelint-prettier/recommended'
],
rules: {
'prettier/prettier': true
}
};
Prettier with Markdownlint
To format Markdown files with Prettier, install prettier
and markdownlint-cli
:
npm install --save-dev prettier markdownlint-cli
You can create a script in your package.json
to run Prettier on your Markdown files:
{
"scripts": {
"format:md": "prettier --write '**/*.md'"
}
}
Running npm run format:md
will format all Markdown files in your project using Prettier.
Future Trends in Code Formatting
AI-Powered Code Formatting
As AI and machine learning technologies advance, we can expect to see AI-powered code formatting tools that adapt to individual coding styles and project-specific guidelines. These tools will provide more intelligent formatting suggestions and automate even more aspects of the coding process.
Enhanced Integration with Development Environments
Future code formatting tools will likely offer deeper integration with development environments, providing real-time feedback and formatting suggestions as developers write code. This will further streamline the development process and enhance productivity.
Broader Language Support
As programming languages continue to evolve, code formatting tools like Prettier will expand their support for a wider range of languages and frameworks. This will ensure that developers can maintain consistent code style across diverse projects and technologies.
Best Practices for Using Prettier

Setting Up Project-Specific Configurations
While Prettier’s default settings work well for many projects, customizing Prettier for your specific project can enhance its effectiveness. Tailoring Prettier’s configuration to match your project’s coding standards ensures that the codebase remains consistent with the team’s agreed-upon style.
Using Different Configurations for Different Projects
If you work on multiple projects with different coding standards, you can create project-specific Prettier configurations. By placing a .prettierrc
file in the root of each project, you can ensure that each project is formatted according to its unique requirements. This flexibility allows you to maintain consistency within each project without imposing a single style across all projects.
Extending Configurations
Prettier configurations can be extended and shared across different projects. For example, if your organization has a standard configuration, you can extend it in individual projects by using the extends
field in your .prettierrc
file. This ensures that all projects follow the organization’s base standards while allowing for project-specific adjustments.
Collaborating with Teams
Collaboration is key to maintaining a consistent codebase. Prettier can play a crucial role in fostering collaboration by eliminating formatting disputes and ensuring that everyone adheres to the same coding standards.
Establishing Team Agreements
Before implementing Prettier, it’s important for the team to agree on the coding standards to be enforced. Discussing and deciding on these standards collectively ensures that everyone is on board and understands the reasons behind the chosen configurations. This agreement forms the foundation for consistent code formatting across the team.
Training and Onboarding
When introducing Prettier to a team, especially if some members are unfamiliar with it, provide training and resources to help them get up to speed. Conduct workshops or create documentation that explains how to use Prettier, its benefits, and how to integrate it into their workflow. Proper onboarding ensures that all team members can effectively use Prettier from the start.
Prettier in Different Environments
Prettier can be used in various development environments, including integrated development environments (IDEs), text editors, and command-line interfaces (CLIs). Ensuring that Prettier is correctly set up in each environment enhances its effectiveness and convenience.
Prettier in IDEs and Text Editors
Most modern IDEs and text editors support Prettier through plugins or extensions. For example, Visual Studio Code has the Prettier – Code formatter extension, while JetBrains IDEs have built-in support for Prettier. Setting up these plugins to format code on save can significantly streamline your workflow by automatically applying the configured style.
Using Prettier in CLI
For developers who prefer using the command line, Prettier can be run directly from the CLI. This is particularly useful for automated workflows and CI/CD pipelines. By adding Prettier commands to your build scripts, you can ensure that code is formatted consistently before it is deployed or merged.
Prettier with TypeScript
Prettier’s support for TypeScript makes it an excellent tool for maintaining consistency in TypeScript projects. Given TypeScript’s strict typing and complex configurations, ensuring that the code remains readable and consistent is crucial.
Configuring Prettier for TypeScript
To configure Prettier for a TypeScript project, you can create a .prettierrc
file with settings tailored to TypeScript’s syntax and features. Here’s an example configuration:
{
"parser": "typescript",
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2
}
This configuration ensures that TypeScript-specific syntax is correctly formatted and adheres to the project’s coding standards.
Integrating with TypeScript Linter
Combining Prettier with a TypeScript linter like TSLint or ESLint provides comprehensive code quality checks. Using prettier-eslint
or prettier-tslint
, you can integrate Prettier’s formatting with your linting rules, ensuring that both style and syntax are consistently enforced across the codebase.
Prettier for Legacy Codebases
Integrating Prettier into a legacy codebase can be challenging, but it is highly beneficial in the long run. Consistently formatted code improves readability, making it easier to maintain and extend older projects.
Gradual Integration
For large legacy codebases, applying Prettier all at once may be impractical. A gradual integration approach is often more manageable. Start by formatting new and modified files, and progressively apply Prettier to the rest of the codebase. This method ensures that new code adheres to the standards while gradually bringing older code up to par.
Addressing Potential Issues
When integrating Prettier into a legacy codebase, be aware of potential issues such as merge conflicts and significant diffs. Communicate with your team about the changes and establish a strategy for resolving conflicts. Using feature branches to apply Prettier incrementally can help manage these challenges effectively.
Leveraging Prettier for Non-JavaScript Files
Prettier’s support extends beyond JavaScript, making it a versatile tool for formatting various file types. Ensuring consistent formatting across all files in your project enhances overall code quality.
Formatting HTML and CSS
Prettier supports HTML and CSS, ensuring that your front-end code is as consistent as your JavaScript. By configuring Prettier to format HTML and CSS files, you can maintain a uniform style across your entire web application.
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 2,
"htmlWhitespaceSensitivity": "css"
}
Formatting Markdown and JSON
Prettier can also format Markdown and JSON files, which are commonly used for documentation and configuration. Ensuring consistent formatting in these files makes them easier to read and maintain.
{
"printWidth": 80,
"proseWrap": "always",
"tabWidth": 2
}
By configuring Prettier for Markdown and JSON, you ensure that all aspects of your project, from code to documentation, adhere to a consistent style.
Conclusion
Using Prettier for consistent code formatting is a powerful way to maintain readability and quality in your software projects. By automating the formatting process, Prettier saves time, reduces errors, and ensures a uniform style across your codebase. Whether you’re working on a small project or a large-scale application, integrating Prettier into your development workflow will help you achieve cleaner, more maintainable code. Stay informed about the latest developments in code formatting tools, and continue to refine your practices to keep your codebase healthy and consistent for years to come.
Read Next: