问题描述:

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?

网友答案:

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.

网友答案:

While this doesn't strike me as the most ideal solution, you can require your external files, and then require their registered module names in the inner block.

JSFiddle Example

require(
    ['require','http://documentcloud.github.com/underscore/underscore-min.js'],
    function(require){
        require(['underscore'],function(_){
            var a = _.intersection([1,2,3],[2,3,4]);
            document.write("Underscore is available in the closure : " + a);
        })
    }
)

It might not look pretty, but that might be a recommended pattern for loading up initial assets so that they can be required intuitively in dependent modules.

相关阅读:
Top