The ratio of time spent reading (code) versus writing is well over 10 to 1 … (therefore) making it easy to read makes it easier to write. -Bob Martin, Clean Code
Formatting code and adhering to style guides can be a time-consuming and meticulous task. I remember when I first started programming, I would count the number of times I pressed the space bar when I wanted to indent on a new line. And at the end of every line, I would check for semi-colons and trailing commas. Thankfully, those days are over. I have found two well-known extensions that can scan your code and reformat it to a very legible and attractive style.
Paulo Ramos created an awesome shell script for this: https://github.com/paulolramos/eslint-prettier-airbnb-react
Prettier is an opinionated code formatter. It supports many languages and integrates with most code editors. You can also set your preferences in the options. Some of the options include tab width, trailing commas, bracket spacing, etc.
I don’t write the best-looking code, but with Prettier I no longer have to worry about that. After a long session of furiously hacking away on my keyboard, I can save my file and then *poof* — it auto-magically formats my code!
ESLint, is program that runs through your code and analyzes it for potential errors. The extension is highly configurable, with an assortment of built-in options for matching your company’s style guide. It can highlight errors while you type in your editor, as well as display an itemized list of errors in your console.
We will set this up so that Prettier will be our main extension for code formatting (based on the ESLint rules we define). Our goal will be to disable all formatting rules inside ESLint so that we will only use it for errors, and have Prettier format all our code instead.
I would also like to preface that at the time of this writing (June 2018), this will not work if you install the libraries globally. In order for this to work, you will have to install ESLint and the other dependencies locally to your project (preferably under devDependencies).
You were able to mediate the conflicting differences between the two, and now they are the best of friends! Our linter will allow us to detect bugs early, and our formatter will help us maintain consistency throughout our codebase. With both these extensions working side-by-side, we should be able to build clean and maintainable code. Your boss will thank you, your peers will thank you, and low-key — Microsoft will probably thank you 🙃
If you have any recommendations or tips, I would love to hear more! 👂
Also, check out my previous post about Essential Customizations for VSCode!