【问题标题】:_ is not defined - NodeJS + UnderscoreJS_ 未定义 - NodeJS + UnderscoreJS
【发布时间】:2019-07-02 14:49:22
【问题描述】:

尝试在 Node.JS 项目中使用 Underscore JS。真的很难过为什么它不起作用。注意:如果我只是将 CDN 用于下划线,这可以工作。 但是我真的很想知道为什么我无法使用 NPM 让它工作。

我收到此错误:

Uncaught ReferenceError: _ is not defined

安装:npm install underscore --save

在 app.js 文件和索引文件中都尝试了这两种:

var _ = require('underscore')._

var underscore = require('underscore');

甚至尝试在页面渲染中要求它:

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

这是我正在使用的测试:

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

【问题讨论】:

    标签: node.js mongodb express npm underscore.js


    【解决方案1】:

    这样使用:

    var _ = require('underscore')
    

    或全局定义:

     global._ = require('underscore')
    

    示例使用:

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

    如果您使用的是下划线 js 前端,则 CDN 链接或下载并放入 /public/js 文件夹

    <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>
    

    【讨论】:

    • 没有这样的运气:(
    • @AndrewLeonardi ,下划线是 library ,不需要传递给 view as varialble
    • 将其从渲染中取出 - 似乎仍然无法正常工作困惑的脸
    • 谢谢 - 仍然好奇为什么我不能使用 NPM?
    • @AndrewLeonardi,如果对您有用,请点赞并接受我的回答:)
    【解决方案2】:

    除了明显的,你似乎已经尝试了所有方法!

    var _ = require('underscore')
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 2014-04-05
    • 2018-08-23
    • 2022-01-18
    • 2017-11-16
    • 2014-04-24
    相关资源
    最近更新 更多