What's the difference between using require in node console and use script tag in html

元气小坏坏 提交于 2019-12-10 20:42:58

问题


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)


回答1:


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.



来源:https://stackoverflow.com/questions/9132130/whats-the-difference-between-using-require-in-node-console-and-use-script-tag-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!