26

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?

Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188
  • Possible duplicate of [Typescript import/as vs import/require?](http://stackoverflow.com/questions/35706164/typescript-import-as-vs-import-require) – rgvassar Mar 01 '16 at 16:49
  • Possible duplicate of [New es6 syntax for importing commonjs / amd modules i.e. \`import foo = require('foo')\`](http://stackoverflow.com/questions/29596714/new-es6-syntax-for-importing-commonjs-amd-modules-i-e-import-foo-require) – C Snover Mar 01 '16 at 22:18

3 Answers3

16

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.

André Claudino
  • 558
  • 4
  • 18
9
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

Sumeet Patond
  • 91
  • 1
  • 1
4

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.

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.

Brocco
  • 62,737
  • 12
  • 70
  • 76