Referring to JavaScript files in Razor views to get JavaScript Intellisense
-
08-10-2019 - |
Question
Visual Studio offers JavaScript Intellisense. It's smart enough to see that you refer to JavaScript files in your master pages (for example jQuery file) and then offers statement completion in any view of the application. However this doesn't seem to work with Razor. Is there a way to get this working with Razor?
ASPX view engine offers this trick for example: <% /* %><script src="~/Scripts/jquery-1.4.1-vsdoc.js"></script><% */ %>
Solution
You should be able to do something like this:
@if (false) {
<script src="/Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
}
That way the code will never run when the app runs, but VS won't know about the if (false)
, so it will parse the <script>
tag and allow Intellisense to take it into account. The problem with using Razor comments in Razor files is that VS will recognize them and completely ignore anything inside them. For example, this won't work:
@* <script src="/Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script> *@
OTHER TIPS
To prevent compiler warnings about unreachable code, you can further wrap this with a pragma:
@{ #pragma warning disable }
@if (false)
{
<script src="/Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
}
@{ #pragma warning restore }