Prettier in TextMate

February 12th, 2019. Tagged: tools

Prettier is a code formatter, great for following consistent coding conventions with 0 effort. Here's how to add it to TextMate, my text editor of choice.

Install Prettier

Globally, so you take advantage of it in any old directory.

npm install --global prettier

If that doesn't work, you probably need to install Node first. So off to the download page you go and then back to the command above.

Config

This is the one I use, I stole it from React and simplified:

'use strict';

module.exports = {
  bracketSpacing: false,
  singleQuote: true,
  jsxBracketSameLine: true,
  printWidth: 80,
  trailingComma: 'all',
};

Save this somewhere in your path, e.g. your home directory:

~/.prettierrc.js

TextMate

Go to menu "Bundles", then "Edit Bundles", then "CSS", then "Menu Actions".

(Doesn't have to be CSS, Prettier formats a lot of things. I just happen to be working on a CSS file)

Then menu "File", then "New", then "Command" from the dropdown.

Then fill out the stuff as you see on the screenshot:

I choose CTRL+Q shortcut as it already exists as "Format CSS" command, which I'm essentially replacing.

The code you need is:

#!/usr/bin/env ruby18
require ENV['TM_SUPPORT_PATH'] + '/lib/textmate'
error = `/usr/local/bin/prettier --write "$TM_FILEPATH"`
puts error

You also need to have the path to node and to prettier (likely the same) in your TextMate path preferences (menu TextMate / Preferences / Variables / PATH). To tell where node is, type which node.

And this is it - save, and start using!

Running

Open an ugly file:

Press CTRL+Q (or your selected shortcut) and then all is pretty:

Oooor, open a file with an error:

... and see the error, without the need to test in the browser and pull hair:

Bye!

So pretty! And don't forget, Prettier formats JS, JSON and what not. When in doubt, just try it!

Ah, and don't forget Stylelint in your TextMate too.

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov