Code styling and formating are important when writing software. It's more important to make sure that your JavaScript code is readable, because well you can format the whole JavaScript code on one line.
Prettier is a code formatted compatible with languages such as JavaScript, HTML, CSS, YAML, Markdown and GraphQL, and a lot more.
It's also great if the formatting is done automatically, mostly when you are staging changes using git
.
In the React project, install the following dependencies:
yarn add -D prettier
After that, add the .prettierrc
configuration file.
{
"arrowParens": "always",
"bracketSpacing": true,
"embeddedLanguageFormatting": "auto",
"htmlWhitespaceSensitivity": "css",
"insertPragma": false,
"jsxBracketSameLine": false,
"jsxSingleQuote": true,
"printWidth": 80,
"proseWrap": "preserve",
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"useTabs": false
}
If you are working with a team, make sure to agree on the rules of the configuration file.
Next, let's add husky which simplifies the setup to use run scripts on specific git hooks. Here's an example of the pre-commit
git hook.
{
"scripts": {
"prepare": "husky install",
"format": "prettier --write .",
"test": "jest"
},
"devDependencies": {
"husky": "^6.0.0",
"jest": "^26.6.3",
"precise-commits": "^1.0.2",
"prettier": "^2.3.0"
}
}
Create a directory called .husky
and inside this directory add the following file called pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn precise-commits
The yarn precise-commits
will reformat the exact code and will only deal with code formatting with prettier
.
And the configuration is done.
To test the configuration, try the following commands:
git add.
git commit -m 'test commit with husky'
And Voilà.
Article posted using bloggu.io. Try it for free.