All notes


RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node.

It implements the Asynchronous Module API.

<!-- ---------- main.html -->

<!-- data-main attribute tells require.js to load
     scripts/main.js after require.js loads. -->
<script data-main="scripts/main" src="scripts/require.js"></script>

<!-- ---------- main.js -->

<!-- Inside of main.js, you can use requirejs() to load any other scripts you need to run. This ensures a single entry point, since the data-main script you specify is loaded asynchronously. -->

requirejs(["helper/util"], function(util) {
    //This function is called when scripts/helper/util.js is loaded.
    //If util.js calls define(), then this function is not fired until util's dependencies have loaded, and the util argument will hold the module value for "helper/util".



Simple Name/Value Pairs

If the module does not have any dependencies, and it is just a collection of name/value pairs, then just pass an object literal to define():

    color: "black",
    size: "unisize"

Example in node node.

//----- varA.js

if (typeof define !== 'function') {
  var define = require('amdefine')(module);

  varA: 'AAA',
  varB: 'BBB'

//----- test.js

var varA = require('./varA');
// { varA: 'AAA', varB: 'BBB' }

Definition Functions

// Does setup work before returning its module definition.
define(function () {
    // Do setup work here
    // wcfNote: after require, the required obj is the object but not the function! That's why we say "do some setup work here", the function is run before being required.

    return {
        color: "black",
        size: "unisize"

Definition Functions with Dependencies

module_id /*optional*/, 
[dependencies] /*optional*/, 
definition function /*function for instantiating the module or object*/

//----- Example

  ['foo', 'bar'], 
  // module definition function dependencies (foo and bar) are mapped to function parameters
  function ( foo, bar ) {
    // return a value that defines the module export
    // (i.e the functionality we want to expose for consumption)
    // create your module here
    var myModule = {
        console.log('Yay! Stuff');

    return myModule;


var varA = require('./varA');
// { doStuff: [Function: doStuff] }