首页 > node.js > 导入http = require('http'); 并从'http'导入*作为http;?

导入http = require('http'); 并从'http'导入*作为http;? (Difference between import http = require('http'); and import * as http from 'http';?)

问题

我一直没能找到一个带有Typescript教程的有价值的NodeJS,所以我在没有指导的情况下潜水,当然我有一个问题。

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

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

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

我明白第一种方法可以让我有选择地从一个模块导入,但如果我导入所有模块,那么两者之间有区别吗?有首选方式吗?如果我从我自己的文件导入,这会改变什么呢?

解决方法

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

问题

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.

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?

解决方法

In the first form, you create an http object in your code (totally clean), then, the interpreter will look for each possible import in http module and append it, one by one, to the http object in your code, this is a little slower (not much) than the second form where you are getting the module.exports object defined in the http module, then copying this reference to a new http object 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.

相似信息