How to download Underscore library with RequireJS?

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

Does not work! ( _ not a function)

How to manage it?

+4
source share
5 answers

Please note that underscore.js is not registered as an AMD module (although it was executed for a short time in earlier versions), therefore it cannot be used in the require () call without any configuration using "shim:" here 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 use.js plugin (if you need to use an older version of require.js).

At the time of writing the current version of require.js is 2.1.8.

Alternatively, you can use lodash.js as a replacement for underscore.js - it registers as an AMD module, so you can use it without additional configuration: http://lodash.com/

+7
source

I think the problem is that the order of the arguments is passed to your callback.

Must be:

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

You also need to use the underscore version 1.2.1, which added this functionality.

+2
source
 require(["underscore"], function() { console.log(_ === window._); }); 
0
source

it all depends on where the script is located. since I do not see that you specified baseUrl, baseUrl will be the default, which means that either 2 things:

  • your script is located directly in the html file, and in your case it will thus look for underscore.js in the same directory as the html file
  • your script is located in the javascript file referenced by your html file, now it will look for underscore.js in the directory of your custom javascript file.

check if the underscore.js file is actually located.

0
source

Here are checkpoints for you to make sure you need to work.

  • Get require-jquery.js and put it in your /js-root dir

  • Add to your HTML, right before the closing </body> : <script data-main="/js-root/main-js-file-name" src="/js-root/require-jquery.js"></script>

  • Get the underscore adapted for AMD and put it in /js-root dir, and

  • In main-js-file-name.js

records:

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

Similarly, in your non-core AMD JS files, when defining a module to use _ , write:

 define(["jquery", "underscore"], function ($, _) { ... return theModuleObjectOrFunction; }); 
0
source

All Articles