RequireJS + Web Essentials Bundling

After a few weeks of using RequireJS, I started to notice slowdown in the initial page loading for our sites.  I found (unsurprisingly) that the browser was making 40+ requests on the first visit because RequireJS makes an HTTP request for each JavaScript module.

I needed to find a way to decrease the amount of requests during production to make the application usable and during development to keep our productivity high.

I searched the web, and I found that the recommended way to optimize the files in Visual Studio was to install node and some other dependencies.  It solved my production problem, but not my development problem.   It got me thinking about how I could get Web Essentials bundling to work to concatenate the files but also have RequireJS load the modules properly.

After heavy experimentation,  analyzing Web Essentials source, and scouring the RequireJS document, I found that it was quite simple to define modules in a way that Web Essentials could blindly bundle.

Here is part of my router file at app/router.js

    define('app/router', function(require, exports, module) {
        'use strict';
        var director = require('director');
        var stringUtils = require('utils/strings');

        // ... CODE

All that we needed to do was to pass the name of the module as the first argument and RequireJS would happily load modules from the same file. In my bundle, I included the main script as the first file in the bundle and pointed my data-main at the bundle.

This makes development very easy since Web Essentials bundles the files each time any of the modules are changed.