Search code examples
javascriptrequirejsjs-amd

require.js: how can I load a module that defines a name under a different name?


I'm trying to load underscore.js with require.js like this:

require(["libs/underscore-1.2.3.js"], function(_) {
    ...
});

But this doesn't work because underscore.js exports a module name: define('underscore', function() { ... }).

Without renaming lib/underscore-1.2.3.js, how can I load it with require.js?


Solution

  • Alright, after some more googling, I've found: https://github.com/documentcloud/underscore/pull/338#issuecomment-3245213

    Where

    @dvdotsenko all AMD loaders allow mapping a module ID to a partial path, usually the configuration is called 'paths', so to do what you want:

       requirejs.config({
           paths:
               underscore: 'js/libs/underscore-1.2.3.min'
           }
       });
       require(['underscore'], function () {});
       

    Since underscore is used by other higher-level modules, like backbone, a common dependency name needs to be used to communicate a common dependency on underscore, and it makes sense to call that dependency 'underscore'. The paths config gives a way to do the mapping to a specific URL you want to use for that dependency.

    This doesn't answer my question (ie, I still don't know how I'd go about loading underscore if all I had was a URL), but at least it's a functional workaround.