0

I have Underscore.js 1.13.2 and I include it using requireJS 2.1.14.

paths = {
'underscore': my_folder_path + "/underscore", // for underscore.js
.. //path of other files
}

I see in the browser's Network tab that underscore.js is loaded. However, I see the below error when I try to use _ in other files.

Uncaught ReferenceError: _ is not defined

Note: my exact same configuration works with Underscore.js 1.6.0 and requireJS 2.1.14

2 Answers 2

1

If you use a module system, whether it is AMD, CommonJS, ESM or browser globals, you need to stick to it. In other words, every AMD module that uses Underscore should import it in the same way:

define(['underscore', ...], function(_, ...) {
    // code that uses _
});

Older versions of Underscore used a lenient, hand-written UMD wrapper which let you get away with mixing browser globals and one other module system. In your case, that meant that as long as there was one module that imported Underscore the AMD way, all modules that were loaded later could assume its presence as a browser global. However, it is important to realize that code written in that way was never valid, even if it worked by accident. The very purpose of a module system is that you explicitly state your dependencies in a consistent way. Moreover, by assuming the presence of the browser global, you make one module implicitly dependent on another module that does the actual import.

Since version 1.10, Underscore is ESM-native and the UMD wrapper is generated by a bundling tool, which is stricter about enabling only one module system at a time. This explains why your (invalid!) setup no longer works. For the same reason, you can no longer use _.noConflict in AMD or CommonJS environments. It never made sense to do such a thing in the first place, but some people mistakenly relied on it, so their code broke down at the 1.10 release.

Perhaps a comforting thought: even if multiple modules depend on Underscore, require.js will load it only once.

0

While upgrading the dependencies of an 8 year old web project using requirejs with underscore & backbone (which depends on underscore), I upgraded underscore from 1.8.3 to 1.12.1 and had the same issue. Backbone was happy, but parts of our code were using the global window._, which as Julian mentioned since 1.10 doesn't work.

My quick fix was to include underscore before including/loading requirejs:

<script src="underscore-min.js"></script>
<script src="require.js"></script>
<script src="require-config.js"></script>

Underscore is now executed twice, once by the script tag, and again by requirejs, but hey, it works!

Not the answer you're looking for? Browse other questions tagged or ask your own question.