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.
import http = require('http') //Common JS
This is Common JS modules. Before version 12.2, this was the only way to use modules in node JS.
import * as http from 'http'; //ES 6
This is ES6 module. In ECMAScript 6 standards, modules are natively supported by Javascript. Node JS implemented this feature in version 12.2.
Out of these two, I always prefer ES6 module because it is part of javascript implementation. ES6 module is also supported by browser. But Common JS is not supported by browser since it is synchronous. AMD module was used in browser before ES 6 because it is asynchronous unlike CommonJS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With