Monday, January 21, 2013

PackScript – Better. Because…

*UPDATE* Check out for a complete reference and examples.

What is this PackScript Jiggery?

PackScript is a powerful open source (MIT license) resource build tool designed specifically for the combining and minification JavaScript, HTML and CSS files in modern, single page web applications. It was built from real need, specifically to support knockout.composite, and is focused around taking all of the pain out of managing all of the resources for your web app. You can find it on github.

PackScript is the next generation of build tools for the web and handles every aspect of building and optimising your web resources. Say goodbye to painful optimisation and to managing code for your debug, test and production environments, say hello to the optimum debugging experience in your browser. PackScript leaves you to do what you do best – code.

Next Generation Build? What makes PackScript better than everything else out there?

First of all, PackScript is much more than a minification tool. It actually delegates the task of compressing resources to separate tools. Microsoft AjaxMin is used by default, but adding support for others is simple. YUICompressor, Closure Compiler, uglifyjs, jsMin and minify are other tools that fall into this category.

So PackScript handles “bundling” together a bunch of files and compresses them. There are a number of existing tools out there that do this…

Server-side Solutions

A significant number of these tools rely on a server side component to dynamically combine and minify your resources. ASP.NET bundling, Carabiner, SquishIt and bundlejs are all examples of this kind of build tool. Generally, they do the job quite well, but they have some drawbacks.

The most obvious issue is that these solutions require a server side component, adding a dependency, tying you to a platform and consuming your valuable CPU cycles. Modern, single page web applications perform rendering tasks on the client, relying on server side processes purely for process and data access. Adding a dependency like this just adds unnecessary complexity.

PackScript produces static resources, as you code and as part of your build process, that can be deployed to any high-performance web server, anywhere, even to a global CDN.

The other not so obvious issue is one of debugging. These tools generally present your debugger with one behemoth file; a less than desirable experience. PackScript allows your files to be packaged in a way that splits your files back up and gives you the debugging experience you need. Even if you are using a server side rendering framework, you can still benefit from PackScript.

Client-side Solutions

Client side tools are not really combining and minifying tools, they optimise the loading of multiple files asynchronously. headjs and labjs are examples of these tools. PackScript will happily coexist with these sorts of tools if you really want to optimise your loading times.

At some point I intend to create an extension that will split your resources into an number of equal size chunks, load them with one of the above tools and piece them together on the client. I’m expecting this to have pretty significant impact on load times!

JavaScript Frameworks

If you’re using a framework like CommonJS or Dojo, they often come with their own set of resource management tools. Use them!

Having said this, PackScript can still offer you some benefits. Read on, and check out the features that PackScript offers.

RequireJS / AMD

RequireJS is arguably the best resource management build tool out there (until now…), popular enough and similar enough to PackScript that it deserves it’s own section.

RequireJS essentially allows you to declaratively define dependencies in your code. Dependencies can consist of individual JavaScript files or you can define named modules that can themselves have dependencies. Modules implement the Asynchronous Module Definition API. RequireJS will ensure that all dependencies (including nested dependencies) have been fulfilled.

AMD is a good standard that is gaining popularity. It takes a lot of the pain out of managing complex dependency trees, and RequireJS minifies your resources along the way. We think PackScript is better for many situations, and can actually coexist with an AMD approach.

Two main problems that RequireJS has are that it’s intrusive and that it introduces a degree of friction.


By intrusive, I mean that you have to write code in a specific way to satisfy RequireJS; modules must be defined and dependencies must be declared using the AMD API. This is not all bad, enforcing a consistent approach to this sort of stuff is not a bad idea, but it introduces a direct dependency on a third party product and unnecessarily ties you to an API.

PackScript manages your dependencies externally to your code and builds static, optimised files at build time. No code needs to be written to manage resources that will ever make it into your running application.


Friction is anything that consumes your time, most often repetitive and error prone tasks – a “force resisting relative movement”. As an example, creating an optimised set of resources with RequireJS involves creating a configuration file and executing the optimiser against that new file. We also need to make sure the build process includes creation of this resource set, so update the build configuration for each environment.

This sort of friction can (and should) usually be eliminated with some custom solutions – create an executable that scans our project folder for build profiles that conform to a specific convention and execute the optimiser against them with a common set of arguments.

PackScript is focused around eliminating friction. It builds your application in the background as you work and is designed to be easily integrated with any automated build process. In most cases, you can just add your resources to the project and move on. If not, add a simple configuration file and PackScript does the rest, even as you code.

Flexibility and Extensibility

PackScript also offers a great deal more flexibility and extensibility than RequireJS.

Don’t like the API? Change it.

Doing the same configuration over and over? Abstract it out.

Optimising the buggery out of your resources? Load multiple modules from one combined script at key points in the application lifecycle, or in the background after loading a set of bootstrapper resources.

Got a stack of icons that are loaded individually? Combine them into a single file and generate a CSS map for them. Add an icon to your project and it’s there. Frictionless.

PackScript works with any static resource and is easily extensible with either JavaScript or .NET. Combine this with the declarative dependency management of knockout.composite, and you get the best of it all.

What Are You Waiting For?

Head over to the feature overview for PackScript, check out an example, have a look at the core unit tests and integration tests, download it from github and have a play! It’s worth noting there are a number of issues on github.

What do you think? Have I missed anything? Is there another solution that’s not mentioned here?

Thursday, January 17, 2013

PackScript – An Example - Freedom From Script Tags!

*UPDATE* Check out for a complete reference and examples.

We’re guessing you got here from the last post. If not, it’s probably worth reading for a quick intro, but hey, you’re smart, you’ll probably pick it up as we go along.

This example demonstrates how to use configuration files to define script and stylesheet outputs in both debug and production forms, create reusable functions and use templates.

As promised, we’re going to show you how we can work on our code in separate files and be able to edit, create, move etc. these files on the fly and have full debugging experience without needing to ever manage script or stylesheet references.

Chrome is currently the only browser that supports this technique using the sourceURL tag. FireBug claims to, but I haven’t been successful. You do use Chrome for web development, right?

The Sample

We’re going to build a silly little text animation thing. Head on over to the github repository and have a quick squiz at what’s there… Oh. Couldn’t be bothered? OK, well, it looks something like this.


At least that’s what it looks like in VS2012.

The Build folder is where our combined files are going to end up. They’re not included in the solution, otherwise search operations in Visual Studio return duplicate results. It will get generated as part of your build process, anyway!

The Tools folder contains a copy of the PackScript assemblies.

The Source folder isn’t really that interesting either. It’s got jQuery, some CSS, a controller file that handles a button click and a simple animate function. Enough to demonstrate what we’re trying to get at.

The html files contain a simple page from which to trigger our animation. They contain duplicate markup, the solution to which lies with our friend knockout.composite.

The Interesting Bits

Firstly, let’s have a look at the PackScript config file, pack.js.

    to: 'Build/site.js',
    include: 'Source/*.js',
    prioritise: 'jquery.js',
    template: 'debug'

    to: 'Build/site.min.js',
    include: 'Source/*.js',
    prioritise: 'jquery.js',
    minify: true

    to: 'Build/site.css',
    include: 'Source/*.css'

A little bit going on here, but pretty easy to follow.

First up, build site.js from all the JavaScript in the Source folder, put jQuery first and apply some template called ‘debug’ to them. Didn’t I see some debug template thingy before?

The production version, site.min.js, is pretty similar, except rather than applying the template, minify it all. We could have minified the CSS too, but you get the idea.

The Template

So it looks like there are two parts to the template. Since you’ve read the first part, you can already guess what each file is for. debug.template.js:

window.eval("<%= prepareContent(content, pathRelativeToConfig) %>");

Looks suspiciously like a very short template. What’s this prepareContent stuff?

this.prepareContent = function (content, path) {
    return content
        .replace(/\r/g, "")                 // exclude windows linefeeds
        .replace(/\\/g, "\\\\")             // double escape
        .replace(/\n/g, "\\n")              // replace literal newlines with control characters
        .replace(/\"/g, "\\\"")             // escape double quotes
        + "\\n\/\/@ sourceURL="             // append sourceURL tag
        + path.toString().replace(/\\/g, '/');

Ahh. Cool, we can put reusable functions into these “configuration” files, like debug.pack.js.

Note we attach our prepareContent function to the “this” object. PackScript restricts the scope of the execution of each file to help avoid conflicts, so to make something available globally, we need to explicitly attach it to the global object. Having said this, when you write them, organise these sorts of functions into pseudo-namespaces. Do it. Thank me later.

So what is actually going on here? The template is wrapping the script content in a call to window.eval. This gives us the chance to inject some content, in this case, a neat little tag that Chrome will interpret. There’s some other stuff in there to make it play nicely with an eval statement, pretty straightforward stuff.

The other magic variables used in the template are passed to the template engine by PackScript. Check out the github readme for an up to date list of the built in variables.

The Result?

You can see the “debug” version here and the “production” version here. Open DevTools for the debug version and you can see our scripts nicely in the source list.


The lack of an ‘S’ on Source is a tad conspicuous (DevTools bug?), but other than that, everything looks as expected. This might seem trivial with only three files (one of which you should probably load from a CDN anyway), but when you have hundreds of source files, it is sweetness to see them arrayed out in neat organisation.

Let’s add a file without adding a script reference.


Cool. Looks like it works. Breakpoints even play the game. The production version works pretty much as you would expect.

So there you have it! Nicely separated code that you can mess with to your heart’s content, debug and production versions, combined CSS, and all without ever having to touch a script tag again*. Feels good.

* - OK, maybe occasionally.

Just To Make It Perfectly Clear…

None of this sample is necessarily “best practice”. It is presented purely to demonstrate some of the power of PackScript. knockout.composite does use a similar technique for this issue, but has a relatively sophisticated resource management system that takes all sorts of pain away.

PackScript is fully functional and under active development. I already have a list of planned enhancements as long as my arm (did someone say “source maps”?), so dip your toes in, give it a try, we think you’ll love it!

In the not-too-distant future, we will cobble together some sort of reference site that shows how to get some serious power out of knockout.composite and PackScript and how it fits very nicely with a SOA flavoured system.

In the meantime, we will be putting together some more posts on how it’s built (JavaScript core running in a Windows console), extensibility and some other advanced stuff.

What would you like to hear about most?

Labels: , , , , , , , , , , , ,

Tuesday, January 15, 2013

PackScript – Next Generation Build for the Web

*UPDATE* Check out for a complete reference and examples.


PackScript is a powerful open source (MIT license) resource build tool designed specifically for the combining and minification JavaScript, HTML and CSS files in modern, single page web applications. It was built from real need, specifically to support knockout.composite, and is focused around taking all of the pain out of managing all of the resources for your web app. You can find it on github.

If you’re pretty familiar with these sorts of tools, you might want to have a look at the post on a few reasons why we believe PackScript is better than all current alternatives.

The Story

Too much of my life as a web developer has been spent managing the multitude of JavaScript, HTML and CSS for whatever current project. Keeping track of where that JavaScript function is. Making sure script and link tags reference the right files from multitudes of scripts and stylesheets. Or worse… Keeping all of the JavaScript for a project in one behemoth file in a team environment.

Now remember we need to have different sets of files for each of our development environments. Facilitate debugging in the dev environment, minify but include some debugging or tracing stuff in the test environment, supercharge everything in production. Ok, that’s not so bad.

But wait… Our mobile app uses some (but not all) of the stuff from our desktop site, but needs some custom code to do all that “responsive” bollocks.

To top all this off, our JavaScript codebase is getting pretty big. We could combine it all into one massive file and load it up front, but it would be even better if we could load largish chunks of it as the user hits various parts of the app.

My head hurts. No more!

Powerful and Flexible Configuration API

PackScript is written primarily in JavaScript and runs in an instance of the Google V8 engine, courtesy of the excellent Noesis.Javascript library. It exposes a powerful and flexible JavaScript API for specifying input and output files and other options.

    to: 'site.min.js',
    include: '*.js',
    recursive: true,
    minify: true

PackScript scans the target folder recursively and, by default, picks up any file that ends with ‘pack.js’ and treats it as a configuration file. These files are executed in an instance of a V8 JavaScript engine.

The fact that the configuration is live JavaScript and not just static text allows us to do some pretty cool things.

Convention Over Configuration

PackScript allows you to define powerful conventions about the location and naming of your files. Tell your devs where to put and what to call your script files and forget about those script tags and AJAX calls.

GlobalExcludes = ['*.debug.js', 'admin.js'];
    to: 'site.js',
    include: '*.js',
    exclude: GlobalExcludes

The GlobalExcludes variable can be defined in a configuration file in another location and used throughout your project. You can also create reusable functions and extend the API to your liking by creating custom “transforms”; each property of the object passed to the pack method is a transform, like ‘include’ and ‘minify’.

We will have a reference site for knockout.composite and PackScript released soon that will show you some much more complex examples.

Painless, Seamless Debugging

PackScript is not fussy about your IDE and provides a memory-resident mode where file changes are detected and the appropriate outputs updated automatically. Keep your code neatly split up in separate files, edit and restructure them, refresh your browser and each file is there in your debugger, no messing with script references, all loaded using a single HTTP connection. Isn’t this how it should work?

The example in the next post will show you how you can keep your code in separate files and retain full debugging support (at least in Chrome) without needing to maintain script references. A production-ready script is produced at the same time.


PackScript gives you powerful and extensible templating for your content files. Out of the box, it provides support for underscore.js templates, but you can easily plug in support for other engines like handlebars, mustache or jsRender. More on this later.

By default, the target folder is scanned recursively for files with an extension of ‘.template.*’. A template for wrapping script files in HTML script tags might be called wrapScript.template.html and might look something like:

<script type="text/javascript">

These templates can then be referenced in your pack configurations using the filename without extension.

    to: 'scripts.htm',
    include: '*.js',
    template: 'wrapScript'
Templates can be applied to any file type. A much more useful application of templates is explored in the next post.

Minification is provided out of the box courtesy of the Microsoft AjaxMin library and can be applied to any or all of your script and stylesheet files by setting the minify option to true. AjaxMin gives quite good compression for zero effort and exposes a .NET interface, so it was a good choice for the first supported minifier. Support for Closure Compiler and others is coming, and plugging in your own is easy.


Simple prioritisation is offered by passing a file name or array of file names to the prioritise option. The files passed will be combined first in the order specified. This is enough to satisfy most scenarios, but will be expanded to allow for wildcards, etc.


PackScript offers a great deal of extensibility. Reusable functions will cater for many situations, but custom transforms can easily be created for simple APIs.

APIs implemented in .NET can also be exposed within JavaScript, again thanks to the awesome Noesis.Javascript library. The file access, minification and logging functions are implemented in this way. A simple marker interface is provided for this, more in a future post! If you’re interested in learning more, leave a comment or drop me a tweet.

What’s Coming?

Some extensions coming will include

  • SASS integration,
  • source map integration,
  • build information (build configuration, version, etc),
  • automatic checkout of files from TFS (though it’s arguable that it would be a better option to switch to git than to use it),
  • combining images and icons into a single file with CSS map generation,
  • HTML minification.
A Cool Trick

The console PackScript application also serves as a JavaScript console where you can interrogate configuration, test functions, etc. This feature is provided by a small wrapper for the Noesis.Javascript library - Noesis.Javascript.Extensions. The wrapper also adds support for dynamic invocation and return types to the JavaScript engine.

> Pack.options
  "configurationFileFilter": "*pack.config.js",
  "packFileFilter": "*pack.js",
  "templateFileExtension": ".template.*",
  "logLevel": "debug"

Until Next Time…

I hope this gives you a reasonable idea of the capabilities of PackScript. It’s worth noting at this point that it is a very early release of the product, and while it is well tested, there may be some reliability issues, and many more features on the way.

You can see a more detailed list of configuration options at the github repository. The unit tests and integration tests are also good sources of information.

Head on over to the next post for a neat practical application!

Labels: , , , , , , , , , , ,