node.js import http = require('http'); 的区别 并从“http”导入 * 作为 http;?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35728117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:59:32  来源:igfitidea点击:

Difference between import http = require('http'); and import * as http from 'http';?

node.jstypescript

提问by Corey Ogburn

I haven't been able to find a worthwhile NodeJS with Typescript tutorial out there so I'm diving in unguided and sure enough I have a question.

我一直无法找到一个有价值的 NodeJS 和 Typescript 教程,所以我在无指导的情况下潜入水中,果然我有一个问题。

I don't understand the difference between these two lines:

我不明白这两行之间的区别:

import * as http from 'http';
// and
import http = require('http');

They seem to function the same way but I imagine there's probably some nuance to their behavior or else one of them probably wouldn't exist.

它们似乎以相同的方式运行,但我想它们的行为可能存在一些细微差别,否则其中一个可能不存在。

I do understand that the first approach could let me selectively import from a module but if I'm importing all of the module then is there a difference between the two? Is there a preferred way? What if I'm importing from my own files, does that change anything?

我确实理解第一种方法可以让我有选择地从模块导入,但是如果我导入所有模块,那么两者之间有区别吗?有没有首选的方法?如果我从自己的文件导入,会发生什么变化吗?

采纳答案by André Claudino

In the first form, you create an httpobject in your code (totally clean), then, the interpreter will look for each possible import in httpmodule and append it, one by one, to the httpobject in your code, this is a little slower (not much) than the second form where you are getting the module.exportsobject defined in the httpmodule, then copying this reference to a new httpobject in your code, this is object in a node special function with a particular context, not only an object created in your code with the contents of the module.

在第一种形式中,您在代码中创建了一个http对象(完全干净),然后,解释器将在http模块中查找每个可能的导入并将其一个一个地附加到您代码中的http对象中,这是一个比第二种形式慢一点(不多),在第二种形式中,您获取http模块中定义的module.exports对象,然后将此引用复制到代码中的新http对象,这是具有特定上下文的节点特殊函数中的对象,不仅是在您的代码中使用模块内容创建的对象。

回答by Brocco

While in a node environment where you've configured the module type to be common JS the output will be the same. Other module frameworks will utilize different syntax and by using the first approach you have the flexibility to change that at will.

在将模块类型配置为通用 JS 的节点环境中,输出将相同。其他模块框架将使用不同的语法,通过使用第一种方法,您可以灵活地随意更改。

Also of note about the import * as http from 'http';approach is that it is the ES6 module import syntax, so once you are in an environment that fully supports ES6 your imports will just work.

关于该import * as http from 'http';方法的另一个注意事项是它是 ES6 模块导入语法,因此一旦您处于完全支持 ES6 的环境中,您的导入就可以正常工作。