RequireJs - Define vs Require

Essentially, when you use require you are saying "i want this, but i want all its dependencies too". So in the example below, we're requiring A, but require will search for all dependencies and ensure they are loaded before continuing.

require(['a'], function(a) {
    // b, c, d, e will be loaded
});

// File A
define(['b','c','d','e'], function() {
    return this;
});

General rule of thumb is you use define when you want to define a module that will be reused by your application and you use require to simply load a dependency.


Below is the code that should be inside jquery.my-plugin.js which defines a module called 'jquery.my-plugin' that can be used as a dependency elsewhere.

define(['jquery'], function($) { //jquery is a dependency to the jquery.my-plugin module
    $.fn.myPlugin = function(options) { //adds a function to the *global* jQuery object, $ (global since jQuery does not follow AMD)
        ...
    };
});

Below is a section of code where you want to attach your plugin function to the global jQuery object and then use it ...

require(['jquery.my-plugin'], function() { // jquery.my-plugin is loaded which attaches the plugin to the global JQuery object as shown above, then this function fires

    //the only reason $ is visible here is because it's global. If it was a module, you would need to include it as a dependency in the above require statement
    $('#element').myPlugin(); //the $ refers to the global object that has the plugin attached
});