Moodle AMD implementation

Nowadays, Moodle uses Requerjs (RequireJS is a JavaScript file and module loader) loader for managing JS modules. This allows us to conveniently manage JS dependencies between individual scripts, as well as separate the scope of instances.

This documentation provides an excellent description and examples of connecting AMD modules in Moodle Javascript Modules

Below I give examples of connecting JS in all possible ways.

  1. Сonnecting AMD script
// local/plugin/amd/src/main.js 
define([
    'local_plugin/config',                        // Shim config
    'local_plugin/lib',                           // Regular AMD lib
    M.cfg.wwwroot + '/local/plugin/js/lib.js',    // Direct call AMD lib
    'lib'                                         // Not AMD lib
    ], function(config, commonLib, DirectCallLib, ShimLib) {
            console.dir(commonLib);
            console.dir(DirectCallLib); 
            console.dir(ShimLib);

            require([url], callback);


        }
    };
// local/plugin/amd/src/config.js requirejs config file extensions
define([], function() {
    window.requirejs.config({
        paths: {
            "lib": M.cfg.wwwroot + '/local/plugin/js/lib', // Define JS location 
        },
        shim: {
            'lib': {exports: 'count'},                      // Define export variable
        }
    });
});
// local/plugin/amd/src/lib.js  library with full AMD support
(function(name, definition) {
    if (typeof module != 'undefined') module.exports = definition();
    else if (typeof define == 'function' && typeof define.amd == 'object') define(definition);
    else this[name] = definition();
}('mod', function() {
    //This is the code you would normally have inside define() or add to module.exports
    return {
        sayHi: function(name) {
            console.log('Hi ' + name + '!');
        }
    };
}));
// local/plugin/js/lib.js  library with full AMD support
(function(name, definition) {
    if (typeof module != 'undefined') module.exports = definition();
    else if (typeof define == 'function' && typeof define.amd == 'object') define(definition);
    else this[name] = definition();
}('mod', function() {
    //This is the code you would normally have inside define() or add to module.exports
    return {
        sayHi: function(name) {
            console.log('Hi ' + name + '!');
        }
    };
}));

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.