Perfect code, zero effort

Autofix JavaScript style issues using jscs.

Here is how to have perfectly styled JavaScript code with zero effort.

Add JavaScript Code Style to your project

npm install --save-dev jscs

Add "style" command to your package.json with an option to automatically fix problems

package.json
1
2
3
4
"scripts": {
"test": "eslint . && npm run style",
"style": "jscs *.js --fix"
}

In the above example I will also run style check after running eslint.

Create a configuration file, I use the default .jscsrc filename

{
  "preset": "yandex",
  "validateIndentation": 2,
  "disallowMultipleVarDecl": {
    "allExcept": ["undefined"]
  }
}

I found that yandex style guide is the closest to what I like among all other preset options. There are a few additional options I use to get the style the way I want it.

Imagine my project has the following source file foo.js

foo.js
1
2
3
4
// my function foo
function foo() {
return "foo";
}

Notice the wrong indent and double quotes. Maybe I pasted this code from somewhere. Now run the style command

npm run style

The file foo.js has been changed; the white space issues have been fixed automatically.

foo.js
1
2
3
4
// my function foo
function foo() {
return 'foo';
}

Perfect code, zero effort.

I advise running style command on each commit, which is simple to do using pre-git

npm install --save-dev pre-git
package.json
1
2
3
{
"pre-commit": ["npm run style"]
}