To run jslint as a rake task in your Rails project, you’ll only need a few things:
- the Java runtime
- jslint itself
- a rake task to invoke it
So let’s get it set up. First, the java. Drop into a shell on your development system (or build system, wherever you want to run jslint), and make sure you have access to the java runtimes (run java -v, or which java). If not, go get it. Don’t be afraid, it’s easy.
Now you need Crockford’s jslint code. There are two parts: one is jslint.js, and the other is the Rhino extension (rhino.js). We will need both of these, and I’ve found it’s easiest when they are combined into one. Concatenate rhino.js to the bottom of jslint.js and save as vendor/jslint.js.
Hey, we’re almost there! Now you just have to add the rake task to your project.
Drop this code into an existing Rakefile, or rake task. If you don’t have any rake tasks, then simply save this as lib/tasks/jslint.rake. Rake will find it in your project automatically. Run rake -T to confirm.
A short explanation: it finds all the js files you want to inspect, and runs jslint on them one at a time, printing out failures. Line 6 is the key line - you can change two parts of this to suit your project. First, the list of files to check is created using a Dir glob. My example gets all *.js files under /public recursively (**). Then the second part of that line is used to reject js files you DO NOT want to inspect. Frameworks, 3rd party code, for example (although it can be fun to run jslint on your framework code to see their level of quality). This example excludes the ExtJS installation.
Now youre ready to run
Enjoy command-line jslint. And if you develop using TextMate, I highly recommend integrating jslint into that as well.
(I’ve been thinking and talking about this for too long. Inspiration to finally get command-line jslint set up came from reading this stackoverflow earlier today.)