Categories
Articles

Setting up Prettier on Spacemacs

In this post, we are going to see how we can setup prettier for Spacemacs and also to auto format while saving your files.

What is Spacemacs?

Spacemacs is a community-driven Emacs distribution. It is a new way to experience Emacs with a sophisticated and polished set-up focused on ergonomics, mnemonics and consistency.

What is Prettier?

Prettier is an opinionated code formatter which supports many languages and integrates with most editors. It can be installed through npm. It is recommended to install prettier globally in your system so that your editor integrates it properly and can be even made to auto formatted while saving your files.

How to setup prettier?

Make sure you installed prettier globally on your system before following the below steps.

If you are using yarn package manager, you can install it with:

Get the develop branch of Spacemacs. Usually it will be located in your home directory under ~/.emacs.d

Add the prettier layer to dotspacemacs-configuration-layers

Add/update javascript layer with prettier as the javascript-fmt-tool. We are going to set prettier as the value for this. This variable tells which is the formatter to format a JavaScript file. Possible values are ‘web-beautify’ and ‘prettier’.

Create a js2-mode-hook to run prettier while saving your files. We are using the js2-mode-hook here because that is the major mode in which javascript files are opened.

If you want to know what is the list of modes you are currently working in like the major mode and the minor mode names, you can use the describe-mode command to know the same. You can either use the shortcuts C-h m or <Space> h d m to run the describe-mode command.

We are going to make use of the before-save-hook for the same. It is a normal hook that is run before a buffer is saved to its file.

References: