by Mads Kristensen via .NET Slave on 10/28/2009 11:10:00 PM
In the past few days, I’ve worked on finding a way to do static code analysis on JavaScript files.The resaon is that I want to apply some sort of binary and source code checking like FxCop and StyleCop provides for C#.
There exist some tools for linting JavaScript like JavaScript Lint, but linting only checks syntax and not implementation. To do that I found the Jscript compiler build into the .NET Framework to be just what I wanted. It compiles JavaScript and reports if it finds any errors.
To test it out, I wrote a simple C# class that takes an array of JavaScript files to compile. I then called the class from a unit test, so I could make the test fail if the compiler finds any errors with the script files. The class contains a single public method called Compile and here is a simplified example on how to use it from any unit testing framework. You can download the class at the bottom of this post.
[Test]public void JavascriptTest(){ string[] javascriptFiles = Directory.GetFiles(@"D:\Website", "*.js", SearchOption.AllDirectories); using (JavaScriptCompiler compiler = new JavaScriptCompiler()) { compiler.Compile(javascriptFiles); Assert.IsFalse(compiler.HasErrors, compiler.ErrorMessage); }}
[Test]
public void JavascriptTest()
{
string[] javascriptFiles = Directory.GetFiles(@"D:\Website", "*.js", SearchOption.AllDirectories);
using (JavaScriptCompiler compiler = new JavaScriptCompiler())
compiler.Compile(javascriptFiles);
Assert.IsFalse(compiler.HasErrors, compiler.ErrorMessage);
}
What’s nice is that by doing compile time checking of JavaScripts, I get that extra little security that’s so hard to get when developing JavaScript heavy websites. The Microsoft JScript compiler isn’t perfect, so I still recommend using a linting tool as well. The two approaches cover different scenarios. I hope to have a very simple implementation on using a linting tool soon.
Remember to add a reference to Microsoft.JScript in your Visual Studio project before using this class.
JavaScriptCompiler.cs (2,48 kb)
Original Post: Verify JavaScript syntax using C#
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.