4
votes

I am trying to write a RequireJS module that depends on jQuery and a jQuery plugin. I am having trouble to declare these dependencies on module level & settings up the shim config – maybe I missed something, but this how I am trying it:

In my application config, I set the path to my module

requirejs.config({
    paths: {
        // loads modules/myModule.js
        myModule: 'modules/myModule',
    }
});
require(['app']);

Which should now be available in app.js:

define(['myModule'], function (mm) {
    // Do stuff with myModule, now available as mm here
});

But how do declare the dependencies for my module – jQuery and the plugin?

I found this wonderful wiki entry where multiple possibilities are shown, but I don't see how that could fit into my module?

I already got this defined in a separate file:

var require = {
    paths: {
        jquery: 'path/to/jquery',
        plugin: 'path/to/plugin'
    },
    shim: {
        plugin: {
            deps: ['jquery']
        }
    }
};

From the docs:

Also, you can define the config object as the global variable require before require.js is loaded, and have the values applied automatically. This example specifies some dependencies to load as soon as require.js defines require():

But where should I put this configuration? Including it before require.js seems a bit contra-productive – if there are 10 modules with dependencies, then I would need to include 10 separate config files?

1

1 Answers

3
votes

Dependencies are usually defined in the same file as the actual module is defined. shim config is only needed for scripts that are not AMD modules.

Example of a module that has four dependencies:

myModule.js

define([
    'jquery', 
    'plugin', 
    'lib/pluginFrom3rdParty',
    'anotherModule'
], function($, plugin, pluginFrom3rdParty, anotherModule) {
     // instantiate the module and possibly return a value as the exported value for the module.
})