Shared Code with AMD/RequireJS

Asynchronous Module Definition

The Asynchronous Module Definition (AMD) specification provides a framework for defining JavaScript modules and dependencies for predictable loading.

Why AMD?

Our Project

Let's start with a small project:


And some modules in package.json for our Node.js server:

"express":    "3.0.2",
"amdefine":   "0.0.2",
"underscore": "1.4.2"


Our function looks like a basic Node.js backend function with a dependency on underscore.

Wrap Shared Code

Use amdefine boilerplate to make define available to Node.js in "lib-shared/shuffle.js":

Express REST API

Let's create a JSON REST API in "lib-server/server.js" with our new function.


Now, on to the browser...

RequireJS is an AMD-compatible script loader with features including:

RequireJS Main

Let's start with a main insertion point in "index.html".

From here on, there are no other script includes!

RequireJS Configuration

Configure "lib-client/main.js" to point to our client libraries.

Shuffle in the Browser

From here, we can define our client-side JavaScript code and see it in the demo.

Parting Thoughts

At Curiosity Media, we use RequireJS for shared code for:

Beyond this, RequireJS offers a lot more functionality than we've seen here today for managing your entire frontend asset collection.


@ryan_roemer is hiring!