jrburke/almond — pull request #96 by murrayju (2014-11-17 21:20:46+00:00)
Title: Try to use requirejs to load missing dependencies

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.