在node控制台中使用require和在html中使用script标签有什么区别

发布于 2025-01-02 05:30:09 字数 372 浏览 2 评论 0原文

我是js世界的新手,这真的让我很困惑,昨天我开始在我的代码中配合underscore.js,所以我开始在REPL环境中尝试它,我选择使用Node控制台,我想出了var _ = require (./underscore.js),然后一切正常。

今天我尝试使用

有人可以解释为什么,以及如何使用 npm 全局安装 underscore 并在不指定文件位置的情况下 require 它(如 ruby​​ require 模块)

I'm new to the js world, this is really make me confused, yesterday I was started to cooperate underscore.js in my code, so I start to try it in REPL environment, I choose to use Node console, I came up with var _ = require (./underscore.js), then everything works fine.

Today I try to embed it in html by using <script> tag, it seems I don't need to manually var _ = underscore, object _ is already there.

someone can explain why, and how to use npm to install underscore globally and require it without specify the file location(like ruby require Module)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

明明#如月 2025-01-09 05:30:09

主要区别在于,使用脚本标记将文件范围的所有全局绑定添加到页面上所有代码共享的全局范围。当您在网站上编写 JavaScript 时,就好像所有不同的脚本都在一个文件中。

另一方面,Node 的 require 更合理地不以这种方式填充全局范围。相反,它返回一个对象,其中包含模块导出的所有内容;这基本上是模块的名称空间。这就是为什么你必须这样做 _ = require('./underscore.js')。这更好,因为您不必担心不同文件的全局变量冲突。

The main difference is that using a script tag adds all the global bindings of the file's scope to the global scope shared by all the code on the page. When you're writing JavaScript on a website, it's as if all of the different scripts were in one file.

Node's require, on the other hand, much more reasonably does not fill the global scope this way. Instead, it returns an object which contains everything exported by the module; this is basically the module's namespace. This is why you have to do _ = require('./underscore.js'). This is better because you do not have to worry about different files' global variables conflicting.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文