sp00m
sp00m

Reputation: 48807

How to choose the dependencies names when sharing a JavaScript AMD module?

I'm writing a tool that depends on HumanizeDuration.js (could be any other dependency). Using RequireJS, in main.js:

require.config({
  paths: {
    "humanizeDuration": "./path/to/humanize-duration" /* .js */,
    "myTool": "./path/to/my-tool" /* .js */
  }
  // ...
});

In my-tool.js:

define(["humanizeDuration"], function (humanizeDuration) {
  // ...
}});

I would like to share my tool (e.g. on GitHub):

(function (global, factory) {

  if (typeof define === "function" && define.amd) {
    define(["humanizeDuration"], factory);
  } else if (typeof exports === "object") {
    module.exports = factory(require("humanizeDuration"));
  } else {
    global.MyTool = factory(global.humanizeDuration);
  }

}(this, function (humanizeDuration) {
  // ...
}));

The question is: which name shall I choose for the dependency? Since it depends on how developers configured their main.js (for RequireJS), am I wrong?

Here, I chose humanizeDuration, so I could tell developers to use this name, but what if they use another tool that chose humanize-duration for example?

Upvotes: 2

Views: 99

Answers (1)

Louis
Louis

Reputation: 151370

If you know there is a most commonly used name to refer to HumanizeDuration.js as an AMD module, use that, but you can use humanizeDuration if there is no common name or if you cannot determine one. Make sure to document it so that users know what to expect. Then if there is a problem because your tool wants humanizeDuration but another tool wants humanize-duration, the users of your tool can use map:

map: {
  '*': {
      "humanize-duration": "humanizeDuration"
  }
}

This tells RequireJS that everywhere ('*') humanize-duration is required, load the module humanizeDuration instead. Obviously, in this case humanizeDuration is what is in the paths. The whole thing could be mapped in reverse if humanize-duration is in the paths.

Upvotes: 1

Related Questions