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

I was not able to find a useful NodeJS with a Typescript tutorial, so I'm immersed in an unmanageable one and I'm sure I have a question.

I do not understand the difference between these two lines:

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

It seems that they function the same, but I think that perhaps there is some nuance in their behavior, or one of them probably will not exist.

I understand that the first approach allowed me to selectively import from the module, but if I import the whole module, is there a difference between them? Is there a preferred way? What if I import from my own files, something changes?

+7
typescript
source share
2 answers

In the first form, you create an http object (completely clean) in your code, then the interpreter will look for every possible import in the http module and add it one by one to the http in your code, this is a bit slower (not so much) than the second form, where you get the module.exports object defined in the http module, then copying this link to the new http in your code, this is an object in a special node function with a specific context, and not just an object created in your code with the contents of the module.

+4
source

In the node environment where you configured the module type as regular JS, the output will be the same. Other modular modules will use different syntax, and using the first approach you will have the opportunity to change it at your discretion.

It should also be noted that the approach import * as http from 'http'; This is because it is the import syntax of the ES6 module, so when you are in an environment that fully supports ES6, your import will work.

+1
source

All Articles