Site Meter
 
 

Using JSHint inside Visual Studio – the basics

JSHint is great. It’s a linting tool for JavaScript: a simple tool that can very often spot your mistakes before you do. It can save you from a lot of tedious debugging, lets you refactor JavaScript code with greater confidence, and reduces the chances of you deploying broken code to your production server.

I’ve been relying on it day-to-day for the last few months while working on a large JavaScript application, and now I’d be very distressed if I had to work without this instant, zero-effort safety net. So, what does it do?

  1. It identifies definite, objective errors in your code (e.g., mistyped keywords, mistyped variable names, mismatched parentheses, and other syntactical slip-ups) before they end up in your browser.
  2. Optionally, it enforces some basic code style consistency rules (e.g., no trailing whitespace, no use of the == operator, etc.), depending on how you configure it

Feature 2 – enforcing style consistency –  isn’t hugely beneficial for small, single-developer projects. But for longer-lived, multiple-developer projects, your team will surely benefit in the long run from a few consistency guarantees.

Feature 1 – typo detection – is the killer benefit from my point of view. I’ll show you a good example in a moment.

As you can probably guess, there are two common ways to use JSHint on a project:

  • By integrating it into your build process (on a CI server). This enforces team-wide consistency.
  • By integrating it into your IDE. This gives you instant feedback as you code.

My current project uses both, but primarily I appreciate having it in my IDE. So, in this post I’ll focus on a Visual Studio extension that makes it easy. Of course you can also find JSHint plugins for many other IDEs or code editors, such as my other favourite: Sublime Text 2.

Why it matters

Here’s an exaggeratedly simple example. Let’s say you have a perfectly OK function like this:

function averageHeight(heights) {
    var sum = 0, index;
    for (index = 0; index < heights.length; index += 1) {
        sum += heights[index];
    }
    return sum / heights.length;
}
 
var myAverageHeight = averageHeight([1.75, 1.78, 1.82]);

Now you decide you want to rename the function just to “average”, since it’s not really specific to heights at all. So you go ahead and change the function signature. But you forget to the change anything else:

function average(values) { // <-- This is the only line I remembered to change
    var sum = 0, index;
    for (index = 0; index < heights.length; index += 1) {
        sum += heights[index];
    }
    return sum / heights.length;
}
 
var myAverageHeight = averageHeight([1.75, 1.78, 1.82]);

Now you press Ctrl+S to save the changes. In the tiniest fraction of a second, and without waiting to build your server-side code, the JSHint extension I’m about to show you will return its verdict about your file:

image

Well, you’re going to notice this! The first three errors tell you exactly where you’ve forgotten to change “heights” to “values”, and they won’t go away until you fix every last one. The fourth warns you that you’re trying to invoke a function that no longer exists. The fifth tells you it’s quite pointless to have this new “average” function, because nobody uses it.

Even in this simple case it’s very nice to know exactly how many times you forgot to rename the “heights” variable. You can imagine how valuable (and reassuring) it is in more complex refactorings such as extracting a function.

I’m not saying this eliminates the need for automated testing. This merely adds to JavaScript a subset of the kinds of code validity checks that you might be accustomed to in C# or another strongly-typed language.

In addition, the kinds of optional common stylistic rules that JSHint can enforce include:

Possible drawbacks of JSHint

In the interest of balance, let me try to give you advance notice of a few downsides to using JSHint, which actually apply to pretty much any linting tool:

  • It’s best when you’re writing fresh new code. When writing new code files, you can keep them compliant with your rules with little effort right from the beginning. But it’s not easy to start using JSHint on a large legacy codebase, because it will initially report thousands of violations. You can either invest a big chunk of time in cleaning everything up, or you can use /*ignore jslint */ comments to ignore your old files, removing those comments one-by-one as you clean up each file over the long term.
  • It’s reliable, but not deeply sophisticated. JavaScript is fully dynamic, so the linter can’t know whether or not a given object will have a certain property at runtime. So, if for example you’re renaming properties as opposed to variables, don’t expect JSHint to find all the places where the old property name is still referenced. Don’t get caught believing that “no JSHint errors” guarantees “no bugs”.
  • It needs a bit of configuration to give the best results. Depending on how you and your IDE work, you’ll need to toggle a bunch of checkboxes in the early days. You’ll get very annoyed if your IDE persistently inserts or reformats code in a way that violates your JSHint rules. Change the IDE settings or the JSHint settings or both.
  • You need to start tracking global variables. In the long run, this is a benefit not a drawback, but it might feel like extra work at first. If you use third-party libraries whose APIs live in a global (e.g., $ for jQuery, ko for Knockout), you must explicitly tell JSHint about them otherwise it thinks you’re referencing undefined things. Eventually, though, you’ll be glad to have an unambiguous list of your dependencies.

So, what’s JSLint and how does it relate to JSHint?

Historically, JSHint is derived from the longer-established JSLint project from Douglas Crockford. The reason why JSHint exists is just to offer more flexibility: JSHint has a modest set of rules derived from common use, whereas JSLint is stricter and requires you to code exactly like the legendary Mr Crockford does.

The following Visual Studio extension lets you choose between JSLint and JSHint with a simple config option. Try out both and see which one you like.

Integrating JSHint into Visual Studio 2010

Yes, I know Visual Studio 2012 was just released this week! We’ll get to that in a minute. Not everyone upgrades during the first week…

The VS extension I’ve been using for the last few months is called JSLint for Visual Studio 2010. It’s free and open source, and you can install it directly from inside VS. Go to Tools > Extension Manager. Click Online Gallery then in the search box (top-right), enter jslint.

image

Once it’s installed, you’ll find a new menu entry: Tools > JS Lint Options. Personally, I like to set it up like this:

image

image

I’m not even going to discuss the multitude of code style options represented by the big grid of checkboxes. If you’ve coded JavaScript for a while, you probably have plenty of opinions of your own.

Notice that you can export and import configurations as XML files. You’ll probably want to store a standard team-wide setup in source control.

Now when you’ve got a JavaScript file open, any time you hit Ctrl+S, the Visual Studio extension will populate the IDE’s “Error” pane with any issues it found – extremely quickly, because it already has a live JavaScript runtime loaded in memory. Double-click to jump to that line. Either fix it, or modify your config settings to make the linter more tolerant.

Issues with this extension

Of course, it’s not totally perfect. Here are a couple of minor niggles I’ve experienced with this extension:

  • I don’t see a way of making it load project-specific rulesets. This means that all of the projects you work on will need to share the same configuration (or you have to keep importing different configurations manually).
  • It collects errors from every JavaScript file you open. So for example if you open jquery-x-x-x.js to see how something is implemented, JSLint for VS2010 will freak out and report more than 1,000 errors. The errors don’t go away when you close that particular tab, so you must manually right-click on the error list and choose Clear JS Lint Errors. Not a big deal, but adds a touch of friction.

Integrating JSHint into Visual Studio 2012

Unfortunately, there isn’t yet a “JSLint for Visual Studio 2012” on the extensions gallery, or at least not one that I could find. And if you try to download the .vsix file for the VS2010 version, it won’t let you install it into VS2012:

image

So, how come the screenshot earlier in this blog post shows it running in VS2012? Well, I guess the extension’s developers haven’t got round to testing on VS2012 yet, but if you’re impatient and want it installed right now, it’s just a matter of modifying the “manifest” in the .vsix file to make it allow installation. Here’s what I did:

  1. Rename JSLint.VS2010.vsix to JSLint.VS2010.zip. Turns out these things are really zip archives. Extract the files to a temporary folder.
  2. Open extension.vsixmanifest in Notepad.
  3. Find <VisualStudio Version=”10.0″> and change it to <VisualStudio Version=”11.0″>.
  4. Zip all the files back up, and rename the result so it has a .vsix extension.
  5. Install it.

This is totally unsupported, off piste, entirely at your own risk, and no technical support questions will even be acknowledged much less answered. But hey, it seems happy enough on my machine:

image

Hopefully the extension’s developers will get a chance to make VS2012 support official in the near future. Maybe you (yes – actually you!) could submit a patch. This is open source, after all.

22 Responses to Using JSHint inside Visual Studio – the basics

  1. Fredi Machado

    Very nice, thank you!

  2. Love the idea of JS Lint. I’m using Knockout pretty much 100% of the time, but my .js files never have anything but a /// to knockout for intellisense. How do I make a tool like JSHint aware of this library and avoid the “‘ko’ was used before it was defined” error?

  3. Luke

    Hi,

    Thanks for the post.

    I’m the developer for the extension.. Surprised it works like that for 2012.. I converted to the framework for 2012 and couldn’t get it to work and gave up (temporarily).. but maybe I should try again.

    I’m more than happy to accept any patches for the features/bugs – just don’t have that much spare time to develop it myself at the moment.

  4. [comment edited]

    Before you ask, as a frontend developer I find Visual Studio an abomination, but our dotnet people are using an on-build custom tool plus I gave them a nodejs shellscript which literally scans hundreds of files in milliseconds for jsLint (which we do prefer over jsHint) and prints a readable report…

  5. Nick Williams

    I’ve been using JSLint extension for a while, very good stuff.

    @Steve Krille, if you add the following comment to your JS file it won’t complain about knockout’s ko object:

    /*global ko:false */

    I’ve never understood why it’s false instead of true! For more info: http://www.jshint.com/docs/

    @Steve Sanderson, regarding the issue of settings per project: could you workaround this by having some sensible base config in the extension’s options, and then augment per project/file with the JSHint directive comments?

  6. @Nick. Thanks. Started googling and found this declaration that seemed to satisfy the complaining:

    /*global $, jQuery, ko, myUtes*/

  7. Boris Rosenow

    @Steve Krile: You should consider wrapping your globals into a closure:

    (function (ko, $) {
    // your code here
    } (window.ko, window.jQuery));

    Without using JSHint myself, I am fairly sure, it should be satisfied this way. Also you have the benefit to be sure, the ko and $ variables you use don’t change at runtime by some other code which exists on the page.

  8. Paul Duran

    This is awesome info. Thanks for writing this up Steve.

    I’ve been mucking around with the jslint resharper plugin (http://resharperjslint.codeplex.com/) however it’s a little annoying because its not configurable. (“Expected exactly one space between ‘function’ and ‘(‘” – are you kidding me?)

    The benefit of the resharper plugin though is that it underlines the symbols in the file and in the warnings bar.

    For now though, i’ll switch to this extension because I need the configurability that it provides.

  9. Nick Williams

    @Boris, you are correct, this will work andon top of that is generally a neater pattern as it avoids polluting the global namespace

  10. @Boris: you still have to make it assume the “browser” environment, in node/rhino you’re not really happy with a “window”.

    But of course we can further complicate our life, should we really want to:
    “`
    /*jslint browser: true*/
    (function (global, $, ko) {
    alert(“<3")
    }(this, this.jQuery, this.ko));
    “`

    @Paul: no, it's not kidding and when there at least four or five frontend developers on a project not to mention backend people, one man overformatting everything with his mighty spaces is a pain in the back. Also resharper, while marvellously heavy on the resources, still makes glamorous mistakes with javascript code, especially with certain class wrappers :)

    @Luke: please, make it store its properties in the project itself – I am working on a project where there are hundreds of javascript files and we are not allowed to break it up into smaller projects – also modifying all of them is out of the question (especially the ones pulled in by nuget).

    @steve: thanks for the editing :)

    no more spamming for today, I promise

  11. Hi, guys!
    Stumbled over this post from the stats on JSLint for Resharper.
    @Paul: Options are planned during this fall, but you can always use the “default” JSlint way.
    For instance, to disable the “space before ()” message, you add:
    /*jslint white: true */
    to the top of your .js file. (Although that disables all whitespace messages)
    This way also lets you define different options for different script files.

    Cheers for the mention. :)

  12. Mike

    Question: When will JavaScript be a 1st class citizen in VS2012?

    … With intellisence/code completion/code navigation.

    Think it’s “not possible”? Take a look at JetBrains WebStorm. It scans the projects’ .js files and makes code completion & code navigation available for both standard and user-defined functions in *.js files, HTML, etc.

  13. Jiggaboo

    What about VS 2008 users!? :)

  14. Joe

    +1 for javascript intellisense/code completion/code navigation in vs2012 +

  15. today I found for my project JSHint tool and now got known that it can be used even in VS

  16. so nice blog…

    Overnight Air Cargo to Panama. This service usually goes by weight and is used for documents, or any time sensitive materials you want in Panama overnight.
    Air Cargo to Panama, This service usually goes by weight our daily consolidation of air cargo to Panama is a great way to share the space and save on price. We recommend cargo Under to 10 LBS be shipped by air to Panama. As container cargo usually has a $20 price tag just for customs and clearance paperworks.

  17. Stephen

    Great tool, that I cant live without work (VS2010 Pro). At home I use VS 2012 Express for Web. Tried the trick with renaming the version, but is missing the supported version, anyone have any idea how to get it working?

  18. Nicholas Murray

    @Stephen – did you manage to get the extension working with Visual Studio 2012 Express for the Web?

  19. Simon

    Luke has posted a beta of the VS2012 version at http://visualstudiogallery.msdn.microsoft.com/1a417c37-4d6f-43ca-b753-6ea6eb5041fd. Says it will be “a couple of weeks” before he has a stable release.

  20. The JSHint works very good in Visual Studio 2012, I use!

  21. Shiras

    Hi,
    We do have an application where we allow the users to write scripts and we are in the process of writing code to convert the user written functions to equivalent javascripts based on some business rules.

    Now I would like to validate the converted JavaScript functions with JSLint.

    Can you please advice how to do this at runtime for each javascript block at runtime.

  22. Error: This VSIX package is invalid because it does not contrain the file extension.vsixmanifest at the root.