在节点控制台中使用 require 和在 html 中使用脚本标签有什么区别 [英] What's the difference between using require in node console and use script tag in html

查看:62
本文介绍了在节点控制台中使用 require 和在 html 中使用脚本标签有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

今天我尝试使用<script>标签将它嵌入到html中,看来我不需要手动var _ = underscore, object _ 已经存在.

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.

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

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)

推荐答案

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

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

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.

这篇关于在节点控制台中使用 require 和在 html 中使用脚本标签有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆