Using Windows CSCRIPT to compile a Handlebar.js template

I was looking for an alternative to using Node.JS for a JavaScript build process today on a Windows machine. I wanted something that relied as much on natively installed elements of a modern Windows PC as possible so that the build process would be portable.

So, I broke out my rusty Windows Script Host skills.

First, I created a file called, compile.wsf with the following contents:

image

When using cscript.exe, you can execute a more complex combination of scripts and include other script files by using a Windows Script File. The content of the file is an XML definition of jobs. A job represents a unit of work. If you only have one job in a file, the name won’t matter as the script engine will select it by default. If you do have more than one job you’d like to store in a single WSF file, you can use the /Job:{id} parameter of cscript.exe to run a single job.

Using the WSF file, you can include other script files using a script element (much like the script tag in HTML). In the example above, I’ve referenced a local copy of handlebars.js and a custom script called compile.js.

You can also inline script as shown above. After doing a basic check on the number of arguments provided to the script, compile is called, which is from the compile.js script reference.

Compile.js is simple:

image

Using an instance of the FileSystemObject, first the input file is verified to exist. Next, both the input and output files are opened. The Handlebars object is available globally by including it in the WSF definition and is used to precompile the contents of the input file’s template definition. Once compiled, it’s written to the output file and both files are closed.

I threw the three files in a folder called lib, and created a simple batch file called handlebars.bat which called the cscript executable with the Windows Script File shown above as the first parameter and then the values of the other parameters passed along:

image

While this solution only works on Windows, it doesn’t hurt to keep the Windows Script Host in mind when throwing together general repeatable tasks that you:

  • consider too complex for a batch file
  • consider too simple for a full .NET application
  • require usage of existing JavaScript libraries, like Handlebars.js for some work