Saturday, December 10, 2011

Zero-friction Javascript Minification with RequireJS and Express

Most software development efforts involve multiple source code files, and Javascript-heavy web applications are no exception. However, if you want your application to load fast, then you need to combine and minify all those Javascript files somehow. RequireJS is a library that can help with this process by allowing you to define javascript modules and the dependencies between them. In "development mode", RequireJS will download modules individually as they are needed. When all of your scripts are shiny and bug-free you can run the optimization tool which will analyze the module dependencies and create a single, minified Javascript file.

The optimization tool is usually run as part of a build process before deploying the application, but if your application runs on Node.js you can eliminate this extra step. Since the optimization tool is itself a Node.js script, it can be invoked directly from the application's start-up code. Here is what this might look like with the fantastic Express web framework:

In development mode, the application will serve the non-optimized Javascript files from the public folder. In production mode, the RequireJS optimizer will combine and minify the Javascript files and serve the optimized files from the public_build folder. Any other files in the public folder (such as images and stylesheets) will also be copied to the public_build folder, so you don't need to clutter your source code repository with generated files.