requirejs / almond

A minimal AMD API implementation for use after optimized builds
Other
2.42k stars 169 forks source link

Try to use requirejs to load missing dependencies #96

Closed murrayju closed 9 years ago

murrayju commented 9 years ago

I am using almond to produce a library that will be consumed by an app that may or may not use requirejs. My library is written using requirejs, and has several dependencies (i.e. jQuery) that are not included in the compiled result. This is accomplished by setting the path to "empty:" as suggested in the docs. It is expected that the consumer of this library will be responsible for including those dependencies.

To get this to work, I wrap up the almond result with a little shim that checks to see if requirejs is available, and if so calls define() to declare my library module with the dependencies. If not available, it uses the almond output as-is. Here is the code for that:

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // Allow using this built library as an AMD module in another project. That other project will only see this AMD call, not the internal modules in the closure below.
        define(['jquery'], factory);
    } else {
        // No requirejs. We are just a plugin, so no globals declared
        factory();
    }
}(this, function () {
    // almond, and all other modules will be inlined here
    // ...

    // Hack since jQuery != jquery
    if ((window.requirejs === undefined) && (window.jQuery !== undefined)) {
        define('jquery', [], function () { return window.jQuery; });
    }

    // return the main module (this calls almond's require() function)
    return require('myModule');
}));

The final piece is the code change in this pull request. Whenever almond encounters a dependency that it doesn't know about, it first looks to see if it can use requirejs, or find the module as a global, before throwing an error.

jrburke commented 9 years ago

Thank you for taking the time to do a pull request. I do not plan on adding this to almond as I want it focused on providing a plain AMD API for built files. Feel free to keep a fork going though, and to add it to the AMD API shims wiki page.