TypeScript Prettier
Introduction
When working on TypeScript projects, maintaining consistent code style becomes increasingly important as your codebase grows. Manually formatting code is time-consuming and prone to inconsistencies, especially when working in teams. This is where Prettier comes to the rescue.
Prettier is a popular opinionated code formatter that supports many languages, including TypeScript. It automatically formats your code according to a set of predefined rules, ensuring consistency throughout your project.
In this guide, we'll explore how to set up and use Prettier with TypeScript projects, understand its benefits, and learn how to customize it to fit your coding style preferences.
What is Prettier?
Prettier is an opinionated code formatter that enforces a consistent style by parsing your code and reprinting it with its own rules. Unlike linting tools that focus on identifying code quality issues, Prettier focuses solely on formatting.
Key benefits of using Prettier with TypeScript:
- Consistency: Ensures uniform code style across your entire codebase
- Time-saving: Eliminates debates about code style in code reviews
- Focus on content: Lets developers focus on writing code, not formatting it
- Integration: Works well with TypeScript, VSCode, and other development tools
Setting Up Prettier with TypeScript
Let's set up Prettier in a TypeScript project step by step:
1. Installation
First, install Prettier as a dev dependency in your project:
npm install --save-dev prettier
2. Configuration File
Create a .prettierrc
file in your project root to customize Prettier's behavior:
{
"semi": true,
"trailingComma": "all",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2
}
3. Add TypeScript-specific configuration
For TypeScript files, you might want to add some specific configurations:
{
"semi": true,
"trailingComma": "all",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"arrowParens": "avoid",
"bracketSpacing": true
}
4. Create a .prettierignore file
Similar to .gitignore
, create a .prettierignore
file to specify files that should not be formatted:
node_modules
dist
build
coverage
Using Prettier with TypeScript
Manual Formatting
You can run Prettier manually to format your TypeScript files:
npx prettier --write "src/**/*.ts"
This command formats all TypeScript files in the src
directory.
Integrating with npm scripts
Add Prettier commands to your package.json
:
{
"scripts": {
"format": "prettier --write \"src/**/*.ts\"",
"format:check": "prettier --check \"src/**/*.ts\""
}
}
Now you can run:
npm run format # Format all TypeScript files
npm run format:check # Check formatting without changing files
Before and After Examples
Let's look at how Prettier transforms messy TypeScript code:
Before Formatting
// Messy TypeScript code
interface User{name:string;age:number;
isActive:boolean;roles:string[];}
function createUser( name:string,age:number, isActive:boolean=true,
roles:string[]=["user"]) : User {
return {
name,
age,
isActive,roles
}}
const processUser = (user:User) => {
console.log(`User ${user.name} is ${ user.age } years old`);
if(user.isActive){
user.roles.forEach((role,i)=>{console.log(`Role ${i+1}: ${role}`)})
}
}
After Formatting
// Clean, formatted TypeScript code
interface User {
name: string;
age: number;
isActive: boolean;
roles: string[];
}
function createUser(
name: string,
age: number,
isActive: boolean = true,
roles: string[] = ['user'],
): User {
return {
name,
age,
isActive,
roles,
};
}
const processUser = (user: User) => {
console.log(`User ${user.name} is ${user.age} years old`);
if (user.isActive) {
user.roles.forEach((role, i) => {
console.log(`Role ${i + 1}: ${role}`);
});
}
};
VSCode Integration
One of the best ways to use Prettier is to integrate it with your IDE. For Visual Studio Code:
-
Install the Prettier extension:
- Search for "Prettier - Code formatter" in the Extensions tab
- Click Install
-
Configure VSCode to use Prettier as the default formatter:
Create or update your .vscode/settings.json
file:
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
With this configuration, your TypeScript files will be automatically formatted when you save them.
Customizing Prettier for TypeScript
While Prettier is opinionated, you can customize certain formatting rules in your .prettierrc
file:
Common Options for TypeScript
{
"printWidth": 80, // Line length
"tabWidth": 2, // Spaces per tab
"useTabs": false, // Use spaces instead of tabs
"semi": true, // Add semicolons
"singleQuote": true, // Use single quotes
"quoteProps": "as-needed",// Quote object properties only when needed
"trailingComma": "all", // Add trailing commas
"bracketSpacing": true, // Spaces between brackets in object literals
"arrowParens": "avoid", // Omit parens when possible in arrow functions
"endOfLine": "lf" // Line feed only (\n), no carriage returns (\r)
}
Integrating Prettier with ESLint
Many TypeScript projects use ESLint for linting. You can integrate Prettier with ESLint to avoid conflicts:
- Install required dependencies:
npm install --save-dev eslint-config-prettier eslint-plugin-prettier
- Update your
.eslintrc.json
file:
{
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier"
],
"plugins": ["@typescript-eslint", "prettier"],
"rules": {
"prettier/prettier": "error"
}
}
Real-world Example: Setup in a TypeScript Project
Let's see a complete example of setting up Prettier in a TypeScript React project:
Project Structure:
my-ts-project/
├── .eslintrc.json
├── .prettierrc
├── .prettierignore
├── package.json
├── tsconfig.json
├── src/
│ ├── components/
│ │ └── Button.tsx
│ └── App.tsx
└── .vscode/
└── settings.json
.prettierrc:
{
"semi": true,
"trailingComma": "all",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"arrowParens": "avoid",
"endOfLine": "lf"
}
package.json scripts:
{
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"format": "prettier --write \"src/**/*.{ts,tsx}\"",
"lint": "eslint \"src/**/*.{ts,tsx}\" --quiet",
"lint:fix": "eslint \"src/**/*.{ts,tsx}\" --fix"
}
}
Pre-commit Hook with Husky
To ensure that all committed code is properly formatted, you can set up a pre-commit hook using Husky:
- Install Husky and lint-staged:
npm install --save-dev husky lint-staged
- Add configuration to package.json:
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{ts,tsx}": [
"prettier --write",
"eslint --fix",
"git add"
]
}
}
This setup will automatically format and lint your TypeScript files when you commit.
Common Issues and Solutions
Issue: Prettier conflicts with ESLint rules
Solution: Use eslint-config-prettier
to disable ESLint rules that might conflict with Prettier.
Issue: Different team members get different formatting results
Solution: Make sure everyone is using the same Prettier version and configuration files are checked into source control.
Issue: Prettier is not formatting some files
Solution: Check your .prettierignore
file to ensure those files aren't being ignored.
Summary
Prettier is an invaluable tool for maintaining consistent code formatting in TypeScript projects. Its opinionated approach eliminates debates about code style and lets you focus on what really matters—writing good code.
In this guide, we've covered:
- How to set up Prettier in a TypeScript project
- Configuring Prettier for TypeScript files
- Integrating Prettier with VSCode
- Combining Prettier with ESLint
- Setting up pre-commit hooks for automatic formatting
By integrating Prettier into your development workflow, you'll ensure that your codebase maintains a clean, consistent style, making it more readable and maintainable for your entire team.
Additional Resources
Exercises
- Set up Prettier in an existing TypeScript project and format all files.
- Create a custom Prettier configuration that matches your preferred coding style.
- Configure Prettier to work with ESLint in a TypeScript project.
- Set up a pre-commit hook using Husky and lint-staged to automatically format code.
- Compare the differences between your current code formatting and Prettier's output.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)