Project Wide JavaScript Code Styling

JavaScript is one of the hottest technologies in modern time. There are large teams working now on JavaScript projects. Due to a number of programmers involved in development, the code quality degrades and standards are forgotten. Every programmer writes JavaScript in her own way as we lack some standard conventions to follow. To avoid such situations, we have a utility available which is known as JSCS (JavaScript Code Styling). JSCS scans you JavaScript code and finds the styling errors in the code. You can then fix the code and fix it as per the standards. JSCS scans your code as per the standards followed by Google, jQuery, Airbnb, Crockford etc. JSCS is available as node package as well as Grunt task.

Here is the presentation of the whole process:


Fork on GitHub

Install as Grunt Task: 

If you have implemented Grunt in your project, it is easier to use the JSCS Grunt task.
Command:
npm install grunt-jscs --save-dev

Now create your Gruntfile.js at project root as below:
// Gruntfile.js

module.exports = function(grunt) {
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    jscs: {
      src: "src/*.js",          // Source file to be checked
      options: {
          config: "config.json" // See in next step
      }
    }
  });

  // Load the plugin that provides the "jscs" task.
  grunt.loadNpmTasks("grunt-jscs");

  // Default task(s).
  grunt.registerTask('default', ['jscs']);
};

Create config.json for JSCS at project root:
// config.json
{
    "preset": "jquery",
    "fileExtensions": [ ".js", "jscs" ],

    "requireParenthesesAroundIIFE": true,
    "maximumLineLength": 120,
    "validateLineBreaks": "LF",
    "validateIndentation": 4,

    "disallowKeywords": ["with"],
    "disallowSpacesInsideObjectBrackets": null,
    "disallowImplicitTypeConversion": ["string"],

    "safeContextKeyword": "_this",

    "excludeFiles": [
      "test/data/**"
    ]
}

Run the Graunt task
grunt default

Here is the sample output for styling errors:


Here is the sample result for success:


Command line usage: 

To use JSCS as command line utility, install the JSCS node package as:
npm install jscs -g

Now run the utility as

jscs <file_path> --config=config.json

jscs src/app.js --config=config.json

jscs src/app.js --preset=google

We would love to hear from you...

back to top