Prettier: Code formatter [JavaScript]


I would like to introduce how to install Prettier which is code formatter and a configuration to co-exist with ESLint

👽 What is Prettier

Prettier is a code formatter with support for:

  • JavaScript(ES2017), JSX, Flow, TypeScript, JSON
  • CSS, Less, SCSS
  • GraphQL
  • Markdown(GitHub Flavored Markdown)

It ensures that all output code confirms to a consistent style.

Some merits for using Prettier are as follows:

  • Building and enforcing a style guide
  • Easy to adopt
  • Clean up an existing codebase

😼 install

Install with yarn:

yarn add prettier eslint-config-prettier eslint-plugin-prettier pretty-quick husky --dev

🎳 Configuration

.eslintrc

Modify ESLint configuration:

{
"env": {
"node": true
},
"parserOptions": {
"ecmaVersion": 7,
"sourceType": "module"
},
"plugins": ["prettier"],
"extends": ["plugin:prettier/recommended"],
"parser": "babel-eslint",
"globals": {
"describe": false,
"it": false,
"before": false,
"beforeEach": false,
"after": false,
"afterEach": false,
"done": false
},
"rules": {
"strict": "off",
"padded-blocks": "off",
"comma-dangle": "off",
"no-param-reassign": "off",
"arrow-body-style": ["error", "as-needed"],
"no-underscore-dangle": "off",
"no-else-return": "off",
"no-unused-vars": "error",
"dot-notation": "off",
"prettier/prettier": "error"
}
}

package.json

Add the following commands to the package.json to format all files before commit:

{
"scripts": {
"eslint": "eslint src test",
"eslint-check":
"eslint --print-config .eslintrc.js | eslint-config-prettier-check",
"prettier": "prettier --write \"{,!(node_modules)/**/}*.js\"",
"precommit": "pretty-quick --staged"
}
}

.prettierrc

Add a .prettierrc for formatting overrides like this

{
"trailingComma": "all",
"semi": false,
"singleQuote": true
}

🍄 Command

Check conflict rule between Prettier & Eslint

yarn run eslint-check

Run Prettier formatter

yarn run prettier

😎 Special Thanks

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!