Dienstag, 2. April 2019

Make IntelliJ format HTML files nicely (from a frontend developer's perspective)

I am using IntelliJ now with my current job, and I dislike the way it does formatting of HTML files (and of course all the backend and Java developers do not really care the same way I do).

Fortunately I finally figured out how to do it:
  1. Install NodeJS (I recommend doing it using nvm) and Yarn (npm is fine as well, but I prefer Yarn)
  2. Set up a package.json file, e.g. by running yarn init
  3. Install Prettier, Babel-eslint, eslint and eslint-plugin-babel:
    yarn add --dev prettier eslint babel-eslint eslint-plugin-babel
  4. In IntelliJ, go to File > Settings > Plugins > Marketplace and install "File Watchers" and "Prettier"
  5. In IntelliJ, set up File Watchers for HTML under File > Settings > Tools > File Watchers and add a watcher for the file type HTML, set up the arguments --parser html --write $FilePathRelativeToProjectRoot$ and under "Advanced Options" make sure that the options "Auto-save edited files to trigger the watcher" and "Trigger the watcher regardless of syntax erorrs" are unchecked.
  6. Create a .prettierrc file in the project's root directory with at least this configuration: {
      "htmlWhitespaceSensitivity": "ignore"
    }
     - this will prevent Prettier formatting closing ">" characters from inline HTML tags to sometimes end up on separate lines.
Hooray, now IntelliJ does a nice HTML file formatting the way a frontend developer like me can enjoy it.