Format Your Code Using Prettier Like a Pro
Don't be like this guy—don’t be a schmuck.
Why Formatted Code Is Needed
Formatting helps structure the lines of code you write making it easier to read and understand. This is crucial when working on a codebase with multiple developers, all with their own style and preference on how their code is structured. Having a uniformed formatted codebase helps prevent headaches when merging and creates a standard that you and your team can build on.
There are several ways to set up a formatting template for yourself and your team. In this article, we’ll explore one of the more popular options: Prettier.
According to the State of JS 2021 survey, 83% of respondents regularly use Prettier as their formatter of choice, a 13% increase from the previous year's survey. Many prominent teams—such as those at Facebook, Webflow, Jest, Dropbox, Spotify, and PayPal—use Prettier to ensure consistent formatting in their codebases.
Prettier can be configured and run in multiple ways. In this example, I’ll demonstrate how to set up Prettier with a Git hook for automation in VS Code. For more examples and configurations, visit Prettier’s documentation.
Before You Start
While it’s not required, it’s helpful to understand the options you’ll be configuring and what they do. You’ll need to create two files and place them at the root level of your project. Keep in mind that these formatting options are project-specific, so you’ll need to repeat this process for each new project. These files will contain the options you can choose, and you can modify or remove options that don’t fit your project’s needs.
.prettierrc
This file, located at the root level of your project, defines the base formatting rules for Prettier. It uses a JSON structure and can be tailored to your team’s standards. Here’s an example:
.editorconfig
This file ensures consistency in your editor settings even before Prettier runs. It also covers options that .prettierrc does not. Here’s an example:
Setting Up the Workflow
For ease of use, both files can be copied at the end of the article. Once you’ve created and configured the .prettierrc and .editorconfig files, you can proceed. Install these three npm packages to streamline the formatting process:
npm install --save-dev prettier lint-staged husky
Then initialize Husky
npx husky init
These steps accomplish the following:
- Install Prettier for formatting.
- Install lint-staged to format only staged files before committing.
- Install Husky to set up Git hooks for automation.
- Initialize Husky, which creates the necessary dependencies and a pre-commit file.
Configuring New Files
Two additional files need configuration: pre-commit and .lintstagedrc
pre-commit
This file, automatically created by Husky, guides the automation process. It is located inside the Husky folder created during initialization. Configure it as shown below:
.lintstagedrc
Create this file (with no extension similar to .editorconfig and .prettierrc) in the root project folder. It narrows the scope of files Prettier formats through the Git hook. Below is an example, but you can adjust it based on your project’s file types:
Testing the Workflow
Once all four files are in place—.prettierrc, .editorconfig, .lintstagedrc, and pre-commit—you can test the workflow.
- Make a simple formatting change to a .js file (add unnecessary spaces or indents, for example).
- Stage your changes: git add -A
- Commit with a test message git commit -m "Testing formatting workflow"
If everything was set up correctly, your terminal should display a success message, and the formatting changes will be automatically applied.
That's it!
You now have a simple yet effective way to harness Prettier and git hooks to automate the formatting of your code.
I’d love to hear your thoughts! Let me know in the comments if this was helpful or if you encounter any issues—I’m here to help!
Copy Paste File Examples
.prettierrc
{ "arrowParens": "always", "bracketSameLine": false, "bracketSpacing": true, "embeddedLanguageFormatting": "auto", "endOfLine": "lf", "htmlWhitespaceSensitivity": "css", "insertPragma": false, "jsxSingleQuote": false, "printWidth": 80, "proseWrap": "preserve", "quoteProps": "as-needed", "requirePragma": false, "semi": true, "singleQuote": true, "tabWidth": 2, "trailingComma": "es5", "useTabs": false, "vueIndentScriptAndStyle": false }
.editorconfig
# Top-most EditorConfig file root = true # Global settings [*] indent_style = space indent_size = 2 tab_width = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true # Overrides [*.md] trim_trailing_whitespace = false max_line_length = off [*.yml] indent_style = space indent_size = 2 [*.ts] indent_style = space indent_size = 4 [Makefile] indent_style = tab [*.html] indent_size = 2 [*.json] indent_size = 2
The above is the detailed content of Format Your Code Using Prettier Like a Pro. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
