Skip to content
antonkovalyov edited this page Jun 23, 2012 · 2 revisions

This is a whirlwind excursion through JSHint's architecture.

The main public class in JSHint is called Linter. Instances of this class can be used for configuring JSHint, extending it and actually parsing and linting your code.

var Linter = require("jshint").Linter;
var code   = "<your beautiful JavaScript code here>";

// Create a new instance of Linter.
var linter = new Linter(code);

// Now you can teach JSHint about your predefined variables.
// Note that default JavaScript identifiers are already there.
linter.addGlobals({
  jQuery:   false,
  MyPlugin: true
});

// If you have any JSHint extensions, you can attach them
// to the current instance.
linter.addModule(myModule);

// Finally, parse your code.
linter.parse();

Parser

JSHint uses Esprima as its main parser. Once it has a tree it visits all its nodes and fires appropriate events.

Events

JSHint fires events whenever it visits a node generated by Esprima:

linter.on("MemberExpression", function (expr) {
  var prop = expr.property;
  
  if (prop.type === "Identifier" && prop.name === "__iterator__")
    report.addError("E004", prop.range);
});

There are also two special events, lint:start and lint:end, that happen before and after JSHint parses your code.

Modules

You can extend JSHint by adding modules to it. Each module is basically a function that adds event handlers:

// This module errs on any identifier that doesn't starts with 'kitty'.
function myModule(linter) {
  linter.on("Identifier", function (ident) {
    if (ident.name && ident.name.slice(0, 5) !== "kitty")
      linter.report.addError("C001", "More cats please.");
  });
}

You can't extend error codes yet but we'll implement that soon.

Reports

You can add warnings and errors to the final report by using addError addWarning methods:

// First parameter is error/warning code and the second is either
// Esprima range or a line number.
linter.addError("E001", 1);
linter.addWarning("W001", [1, 2]);

All currently supported errors and warnings are defined in the constants.js file. Final report is always available as a linter.report.errors and linter.report.warnings objects. They both have the same structure (type 1 is for errors, type 2 is for warnings):

[
  {
    type: 1,
    code: "E001",
    data: "Trailing comma causes errors in some versions of IE."
  },
  {
    type: 2,
    code: "W001",
    data: "Bitwise operator. (mistyped logical operator?)"
  }
]

We will be adding more information soon. Meanwhile, ask your questions on our mailing list!

Clone this wiki locally