Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load Underscore library with RequireJS?

require(['underscore'], function ($, _) {
  ...
});

Doesnt work! (_ is not a function)

How to manage it?

like image 236
williamv Avatar asked Sep 24 '11 15:09

williamv


2 Answers

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/

like image 197
seanTcoyote Avatar answered Sep 28 '22 16:09

seanTcoyote


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.

like image 26
meirish Avatar answered Sep 28 '22 16:09

meirish