Auto-formatting JavaScript Code Style

Today, we’re going to look at the powerful new auto-formatting feature in JSCS for automatically applying style guide rules in our scripts. This has been in-development for some time and is in my view, a game changer.

JSCS

In a number of the OSS projects we hack on at Google, we love using JSCS for linting JS against rules in our style guide. JSCS excels at catching style issues like mixing spaces and tabs, inconsistent quote marks, trailing whitespace & it can enforce several other validation rules.

My theme of choice is Seti UI in case you’re interested

Auto-formatting JS to match a Style Guide. OMG!

Validation alone is powerful, but as of JSCS 1.12.0, the tool now supports automatically formatting your code to adhere to your style guide. This is freakin’ amazing and really takes style enforcement to a whole other level. Auto-formatting is available by passing the `-x` flag to JSCS.

Auto-formatting JS Code Style in Sublime

Let’s take the code snippet from earlier, which contained issues like inconsistent indentation, missing spaces after opening brackets and operators sticking to expressions where they shouldn’t.

Setup

Assuming you have Node and Package Control already installed on your system:

  • Next, open up the Command Palette in Sublime and type Install Package.
  • When the plugin list displays, search for `jscs format`. Select the entry ‘JSCSFormatter’
  • Install JSCSFormatter. Party!

Usage

From the Command Palette, we can now just select ‘JSCSFormatter: Format this file’ to automatically format the current file based on the rules specified in your JSCS configuration:

Wrapping up

The tooling around JSCS is constantly growing and support has been available for Atom, VIM, WebStorm, Brackets and a number of other editors for a while.

Eng. Manager at Google working on Chrome • Passionate about making the web fast.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store