If you are using Node.js, getting it is as easy as:
sudo npm install -g esprima
esvalidate foo.js bar.js baz*.js
If your files are syntatically valid, checking few megabytes of source should be completed in a second. Thanks to Google V8, Esprima under Node.js is really really fast.
Say you don’t like to depend on Node.js, no need to worry since you can also use the ubiquitous Java. The trick is to leverage Mozilla Rhino. The setup is rather simple; place the three files,
js.jar from Rhino,
esvalidate.js, all in the same directory. After than, run the validator as follows:
java -jar js.jar bin/esvalidate.js foo.js bar.js baz*.js
The above technique should work on Windows, Linux, and OS X. Hate to launch Java that way? Create a shell script or a batch file which wraps it. On Mac OS X, this is even easier since Rhino installation via Homebrew already prepared the wrapper
/usr/local/bin/rhino and the above invocation is therefore simplified to:
rhino esvalidate.jsw foo.js bar.js baz*.js
If you use Vim, you can set
I’m sure it is possible to integrate the validator with other popular editors such as Emacs, TextMate, or Sublime Text. Update: Sublime Text package for the validator is now available, see github.com/duereg/sublime-jsvalidate.
files=$(git diff-index --name-only HEAD | grep -P '\.js$') for file in $files; do esvalidate $file if [ $? -eq 1 ]; then echo "Syntax error: $file" exit 1 fi done
Are you using Grunt for your build workflow? Look no more, install grunt-jsvalidate (which I created some time) and you have a new task
jsvalidate which does the validation just like the above. Of course, under the hook it also uses Esprima.
Running a continuous integration system? There is a support for JUnit XML format as the output. This means, the validation report can be consumed easily by e.g. Jenkins or TeamCity.
With these multiple layers of defense during editing, code check-in, build, and continuous integration, hopefully the chance of making a stupid mistake is significantly reduced. How would you plan to guard yourself with a syntax validator?