Code Formatting in JS, Prettier for the win.
In a recent project at work, I was asked debug some JavaScript code. I went ahead and open some JS files of the project. The formatting of these files was very inconsistent. Some files had tab spacing of 4 others had tab spacing of two, some strings had single quotes, other strings had doble quotes. The list went on and on. It was hard to parse through the files and understand the intent of what the code was supposed to do. After an hour of refactoring the code to a a consistent format, I was finally able to read and understand what was the goal the previous author. I tried to reformat the code with built in tools my editor provided, but the result was not suboptimal. I knew there had to be a better way and after some research I learned about Prettier, and rapidly adopted it across all my projects at work.
WELCOME PRETTIER: https://github.com/prettier/prettier
Prettier is an awesome tool that integrates with a bunch of text editors and helps you format your code. On top of that, you can easily configure prettier to re-format your code on save.
Take for example this JS file, with inconsistencies on semicolons, spaces, quotes etc. It is valid JS but difficult to read.
var a= ( function () {
var foo = 42;
var bar=20
var toolName = "Prettier"
var simpleString='just a string with single quotes'
function display () {
console.log(foo + bar);console.log( toolName)
console.log(simpleString);
}
return display;
})( );Hit Save and this is the result:
var a = (function() {
var foo = 42;
var bar = 20;
var toolName = 'Prettier';
var simpleString = 'just a string with single quotes';
function display() {
console.log(foo + bar);
console.log(toolName);
console.log(simpleString);
}
return display;
})();To find out more and go deeper into the details I recommend to check some of the awesome videos you can find on youtube. This one video in particular, inspired me to play with Prettier. After just a couple of minutes, I was sold on how easy it was to install and use that I told my colleagues at work about it.https://www.youtube.com/watch?v=hkfBvpEfWdA
My team feels relieved and we agree it has definitely liberated some cognitive resources. We can now spend more time thinking about solving great problems and not having to worry about formatting our JS files.