Configure Prettier in your Node JS project

How to configure Prettier to format your code as It was written by only one developer


Aug 08, 2020
featured image

Overview

Prettier is a code formatter that supports many languages and can be integrated with most of the editors.

Also, you can integrate it with your CI/CD.

That way nobody will be able to merge to the master branch if the code is not well-formatted.

With Prettier you will be able to define your own rules, however default rules are enough at the beginning.

Your rules will be defined in a file called .prettierrc placed in your project’s root.

Let’s see how to install Prettier and then make some configurations.

      
npm install prettier --save-dev
  
    

Example of Prettier config file

      
{
  "trailingComma": "es5",
  "tabWidth": 4,
  "printWidth": 120,
  "semi": true,
  "singleQuote": false,
  "useTabs": false,
  "quoteProps": "as-needed",
  "jsxSingleQuote": false,
  "bracketSpacing": false,
  "jsxBracketSameLine": true,
  "arrowParens": "avoid",
  "requirePragma": false,
  "insertPragma": false,
  "proseWrap": "preserve",
  "endOfLine": "lf"
  }
  
    
See more options for the .prettierrc file

Gulp integration

      
npm install gulp-prettier -save-dev
  
    
      
gulp.task("prettier", () => {
  return gulp
  .src("./**/*.js")
  .pipe(prettier(".prettierrc"))
  .pipe(gulp.dest("./"));
});
  
    

PhpStorm IDE integration

If you are using PHP Storm, it’s highly recommended that you configure your IDE to auto-format your code every time you save a .js file

https://prettier.io/docs/en/webstorm.html The plugin will take the rules from you .prettierrc file

Configure a File Watcher in PhpStorm to auto-format the code on save.

Visual Studio Code

You can install the extension as any other and then you can use these configurations in you settings.js with the prefix "prettier"
      
{
  "prettier.useTabs": false,
  "prettier.trailingComma": "es5",
  "prettier.tabWidth": 4,
  "prettier.printWidth": 120,
  "prettier.semi": true,
  "prettier.singleQuote": false,
  "prettier.quoteProps": "as-needed",
  "prettier.jsxSingleQuote": false,
  "prettier.bracketSpacing": false,
  "prettier.jsxBracketSameLine": true,
  "prettier.arrowParens": "avoid",
  "prettier.proseWrap": "preserve",
  "prettier.endOfLine": "lf"
}
  
    

prettier nodejs javascript dev