AndrewLeonardi
AndrewLeonardi

Reputation: 3512

_ is not defined - NodeJS + UnderscoreJS

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>

Upvotes: 0

Views: 1945

Answers (2)

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

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>

Upvotes: 1

nanobar
nanobar

Reputation: 66365

You seem to have tried all except the obvious one!

var _ = require('underscore')

Upvotes: 0

Related Questions