Sunday, August 21, 2011

almond: a small AMD shim loader

I just put up release 0.0.1 of almond, a tiny shim loader for the AMD JavaScript module API. It can be used as a replacement for RequireJS after an optimized build. It is great for standalone libs or tiny apps that want a very minimal footprint with all the benefits of AMD.

From the README:

Some developers like to use the AMD API to code modular JavaScript, but after doing an optimized build, they do not want to include a full AMD loader like RequireJS, since they do not need all that functionality. Some use cases, like mobile, are very sensitive to file sizes.

By including almond in the built file, there is no need for RequireJS. almond is 948 bytes when minified with Closure Compiler and gzipped.

Since it can support certain types of loader plugin-optimized resources, it is a great fit for a library that wants to use text templates or CoffeeScript as part of their project, but get a tiny download in one file after using the RequireJS Optimizer.

If you are building a library, the wrap=true support in the RequireJS optimizer will wrap the optimized file in a closure, so the define/require AMD API does not escape the file. Users of your optimized file will only see the global API you decide to export, not the AMD API. See the usage section below for more details.

So, you get great code cleanliness with AMD and the use of powerful loader plugins in a tiny wrapper that makes it easy for others to use your code even if they do not use AMD.


2 comments:

Drew said...

So does r.js replace RequireJS with this? :D

Actually, does this work in situations where you optimize part of an app, but other modules still need to be loaded over the network?

James Burke said...

Drew: if you have a smallish app that prefers to just bundle all your files up into one file, almond+r.js optimizer can be enough.

Although, I prefer using RequireJS in dev, it can be paired with a partial build. With the optimizer you can leave out one or two files you want to debug as separate scripts and load them dynamically with RequireJS to set breakpoints in just the one module/script.

almond does not do any dynamic loading, if you want that you will need a full AMD loader. The almond README has the list of restrictions and what it supports.