Wolfgang Adamec
Wolfgang Adamec

Reputation: 8524

requirejs: shorten dependency list

I develop a web application with require.js.
As the whole thing grows and grows, some dependency lists of certain amd modules grow also and get very complex (reminds me a bit of the large amount of script tags in the index.html page before I started to use require.js).
So I started to put the core modules - those I always need - in new amd module:

define(["config", "eventObj", "registry", "log", "userObj"], 
  function (conf, event, reg, log, user) {
    var core = {
      conf: conf,
      event: event,
      reg: reg,
      log: log,
      user: user
    };
    return core;
});

But since this change, weird things happen, for example at one time this "core" is there, but later, in another module, where it is also referenced as dependency, it is undefined.
Is there a better way to shorten the dependency list, to group various modules without having to put those things in one file?

Upvotes: 1

Views: 1235

Answers (2)

Asanka
Asanka

Reputation: 427

When you declare paths for the dependencies like this

define(["config", "eventObj", "registry", "log", "userObj"]

It search for the dependencies in the directory where this module is called. So to avoid this kind of scenarios, there is a clean way to define paths in Require.js

require.config({
    baseUrl: "/another/path",
    paths: {
        "some": "some/v1.0"
    }
  });

Now you can use "some" anywhere as a dependency. This is okay for adding dependencies for user modules. But when defining a core module what Janith has mentioned above is more clean. As I see it has shorten the dependency list in way.

Upvotes: 0

janith
janith

Reputation: 1025

We have used a similar approach in BoilerplateJS and this looks much cleaner if you are worried about readability:

define(function (require) {

    return {
        conf : require("config"),
        event : require("eventObj"),
        reg : require("registry"),
        log: require("log"),
        user : require ("userObj")
    };
});

Code adopted from https://github.com/ectechno/boilerplatejs/blob/master/src/core/_boiler_.js

But I don't see why your setup is not working properly. Are you sure you are pointing to the correct paths?

Upvotes: 1

Related Questions