This post is over 6 months old. Some details, especially technical, may have changed.

VS2010/MVC JavaScript Intellisense HTML “Hack”

There is a problem with Visual Studio 2010 JavaScript Intellisense (using MVC in this case) and it is this - If you are referencing JavaScript resources correctly (or Stylesheets for that matter) as you all should be you wont actually get intellisense within an SCRIPT blocks in HTML.  So using this sort of script reference,

<script src="@Url.Content("~/Scripts/json2.js")" type="text/javascript"></script>

Will not give you intellisense.  Sure you can use JavaScript files and make use of the reference VSDOC tag (in fact maybe you should)

/// <reference path=?~/Scripts/json2.js?>

But this doesn't work (yet) within SCRIPT blocks.  So what about those rare times you actually want intellisense within your page?  It's actually quite easy though a bit hacky - stick it in a condition branch that never gets reached.  So,

@if (false) {
<script src="~/Scripts/json2.js" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/json2.js")" type="text/javascript"></script>

The Intellisense parser doesn't really care about the fact that the code wont ever get hit and you still get your typeahead and documentation etc. but it won't ever get accidentally written to the generated output (as often happened to me).  I guess this seems kind of obvious or whatever but perhaps so obvious some people may not have even though about it and hopefully it'll help someone out somewhere at some point sometime, eventually - maybe.

Published in JavaScript on January 07, 2011