How to load Underscore library with RequireJS?
require(['underscore'], function ($, _) {
...
});
Doesnt work! (_
is not a function)
How to ma开发者_StackOverflownage it?
Note that underscore.js doesn't register itself as an AMD module (though it did for a brief time in earlier versions), thus it can't be used in a require() call without some configuration using "shim:" like so:
require.config({
paths: {
jquery: 'lib/jquery.min',
underscore: 'lib/underscore-min'
}
shim: {
"underscore": {
exports: "_"
}
}
});
See the docs at: http://requirejs.org/docs/api.html#config-shim
Before shim:
was added to require.js, you could do something similar with the plugin use.js (in case you need to use an older version of require.js).
As of this writing, the current version of require.js is 2.1.8.
Alternatively, you can use lodash.js as a drop-in replacement for underscore.js - it does register itself as an AMD module, so you can use it with no extra config: http://lodash.com/
I think the problem is the order of args passed in to your callback.
Should be:
require(['underscore'], function (_, $) {
...
});
Also you need to be using underscore version 1.2.1 which added this functionality.
require(["underscore"], function() {
console.log(_ === window._);
});
it all depends where the script is based. since i don't see you specified a baseUrl, the baseUrl will be the default, that means, either 2 things:
- your script is directly inside a html file, and in your case it will thus look for underscore.js in the same directory of the html file
- your script is in a javascript file referenced by your html file, it will now search for underscore.js in the directory of your custom javascript file.
check if the underscore.js is actually there.
Here are the checkpoints for you to make sure what you need works
Get require-jquery.js and put it to your
/js-root
dirAdd to your HTML, right before the closing
</body>
tag:<script data-main="/js-root/main-js-file-name" src="/js-root/require-jquery.js"></script>
Get underscore adapted for AMD, and put it to
/js-root
dir as wellIn
main-js-file-name.js
write:
require(["jquery", "underscore"], function ($, _) {
...
});
Similarly, in your non-main AMD JS files, when defining a module, to use _
, write:
define(["jquery", "underscore"], function ($, _) {
...
return theModuleObjectOrFunction;
});
精彩评论