Search code examples
javascriptmodulerequirejsamd

How to properly publish an AMD module so that RequireJS can locate the dependencies?


AMD is my favorite JS module standard, for the simple reason that it allows the proper specification of module dependencies in an analyzable way. Say my module uses jquery and lodash:

define(['jquery', 'lodash'], function ($, _) { ... });

Now, say I want to publish this module. Of course, I would specify those dependencies in the package.json and/or bower.json files, so I can be sure they will be installed. However, how can I be sure that the jquery and lodash libraries are found by the AMD loader (e.g. RequireJS)?

It seems that users of my library would be forced to specify those paths manually:

requirejs.config({
    paths: {
        jquery: '../lib/jquery/jquery-min',
        lodash: '../lib/lodash/dist/lodash'
    }
});

As an application developer, I would be fine with that. But I cannot just assume that users of my library will automatically do this (let alone with matching names), so I'd have to document the extra step. This worries me. NodeJS / CommonJS seems to have a way of finding the correct file without any path specification. I'm not sure how this is done, but I guess they search in the most likely places.

What is the preferred way of handling this for AMD packages?


Solution

  • There is a tutorial about how to build a standalone library with requirejs here.

    Also take a look at this example.

    Basically you wrap your code with a start and end code segments. And specify it in the config.

    {
        "baseUrl": "../lib",
        "paths": {
            "principium": "../principium"
        },
        "include": ["../tools/almond", "principium"],
        "exclude": ["jquery", "underscore"],
        "out": "../dist/principium.js",
        "wrap": {
            "startFile": "wrap.start",
            "endFile": "wrap.end"
        }
    }
    

    Note that, you exclude the used libraries jquery and underscore because you expect users of your library to include them for you. You tell your users about the dependencies. That is the recommended approach. Though you could omit the exclude and let the dependency be included in your build, that is fine as well.