0

Trying to use Underscore JS in a Node.JS project. Really stumped why it is not working. Note: This works if I simply use the CDN for underscore. However I'd really like to know why I am unable to get this to work using NPM.

I am getting this error:

Uncaught ReferenceError: _ is not defined

Installed with: npm install underscore --save

Within the app.js file & Index files have tried both of these:

var _ = require('underscore')._

and

var underscore = require('underscore');

Even tried requiring it within the page render:

res.render("dashboard", {currentUser: req.user, underscore : underscore});

This is the test I'm using:

<script> 
var tacos = ['beef', 'chicken', 'soft', 'hard', 'With nacho cheese']
 _.shuffle([tacos]);
 console.log(_.shuffle(tacos)); 
</script>

2 Answers 2

1

use like this way :

var _ = require('underscore')

or define globally:

 global._ = require('underscore')

example use :

_.map([1, 2, 3], function(num){ return num * 3; });

if you are using underscore js frontend side then CDN link or download and put in /public/js folder

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
<script> 
 var tacos = ['beef', 'chicken', 'soft', 'hard', 'With nacho cheese'];
 var shuffled =_.shuffle(tacos);
 console.log(shuffled); 
</script>
Sign up to request clarification or add additional context in comments.

6 Comments

No such luck :(
@AndrewLeonardi , underscore is library , no need to pass to view as varialble
Took it out of the render - still does not seem to be working confused face
Thank you - Still curious why I cannot use NPM?
@AndrewLeonardi , please upvote and accept my answer if is useful to you :)
|
0

You seem to have tried all except the obvious one!

var _ = require('underscore')

2 Comments

Tried that one too :D No luck
It does work so you'll have to be more detailed about where it's not working in your code repl.it/@DominicTobias/HummingAmusedProperty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.