• April 15th, 2010

    Modulr: script concatination via CommonJS

    Modulr is a script concatenation tool I’ve been playing with which pre-processes client-side scripts into a single script suitable for deployment. This accomplishes two valuable goals:

    • lets you break your scripts out into discreet chunks for functionality
    • improves performance by minimizing the number of HTTP requests

    Example, assuming this hypothetical directory structure:

    - canvas
    --- tools.js
    - color.js
    - lang
    --- enumerable.js
    - main.js
    

    The content of main.js:

    // Declare your dependencies and assign them to variables.
    var color = require('color');
    var ctools = require('canvas/tools');
    var enumerable = require('lang/enumerable');
    
    // Use your imported scripts!
    var rgb = color.hex2rgb("#C00");
    var myCanvas = ctools.attach("some-canvas-id");
    
    enumerable.each(["stuff", "things", "other"], function(item, i) {
      // ...
    });
    

    As you can see, at the top of the file you simply require the scripts you’d like to use before using them. That’s it, done! Modulr takes care of fetching them and writing them into the file.

    Modulr avoids global-scope pollution

    Note that each require invocation assigns the result to a variable. The scripts which get concatenated via require are trapped within a closure, ensuring that your scripts do not pollute the global scope.

    Modulr makes your code more portable

    Another great thing about Modulr is that if follows the CommonJS API, allowing you to declare your script dependencies in plain old JavaScript. No config files or embedded tokens, just JavaScript. This has the added benefit of making your scripts more portable — as long as your environment supports the CommonJS API (node, narwhal, etc) your scripts will know how to resolve their dependencies.

    Creating a CommonJS compatible module

    In order for a script to work with the CommonJS API it must assign public properties to the exports object.

    The content of color.js illustrates this:

    
    // Define your functionality:
    function hex2rgb(hex) {
      /* ... */
    }
    
    function rgb2hex(rgb) {
      /* ... */
    }
    
    // Attach your API to the exports object:
    exports.hex2rgb = hex2rgb;
    exports.rgb2hex = rgb2hex;
    

    A working example

    To get in and get your hands dirty, check out my working example up on Github. It’s very tiny, and attempts to get the core ideas through as simply as possible.

    http://github.com/dandean/modulr-demo

    Suggestions and corrections are always welcome.

    Posted in Code/Projects, JavaScript, Ruby | 2 Comments »

Un-Dumbify