Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 28, 2022 02:59 pm GMT

How to add Prettier code formatter to your project?

You can use Prettier to make your code more readable and consistent with your style guide. There are several ways to start Prettier automatically, these are the most popular:

1. pretty-quick

Use library pretty-quick to format your changed or staged files.

npx husky-initnpm install --save-dev pretty-quicknpx husky set .husky/pre-commit "npx pretty-quick --staged"

2. Shell script

Save this script as .git/hooks/pre-commit and give it execute permission:

#!/bin/shFILES=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g')[ -z "$FILES" ] && exit 0# Prettify all selected filesecho "$FILES" | xargs ./node_modules/.bin/prettier --ignore-unknown --write# Add back the modified/prettified files to stagingecho "$FILES" | xargs git addexit 0

If git is reporting that your prettified files are still modified after committing, you may need to add a post-commit script to update gits index.

Add something like the following to .git/hooks/post-commit:

#!/bin/shgit update-index -g

Configure rules

Create a *.prettierrc file at the root of your project to configure your prettier rules.

Here's an example file containing some popular rules:

{  "semi": true",  "trailingComma": "all",  "singleQuote": true,  "printWidth": 70,  "arrowParens": "always",  "tabWidth": 2}

For everything you don't want to format, create a .prettierignore file:

node_modules/package.json

Manual Run & Fix

To manual run via CLI, add a command to package.json and run npm run format.

{ "scripts": {  "format": "prettier --write ." }}

Original Link: https://dev.to/dobron/how-to-add-prettier-code-formatter-to-your-project-5coh

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To