2

I know that var someModule = require('someModule') is generally replaced by import * as someModule from 'someModule' but I can't figure out how to use Typescript/ES6 syntax to express the following Node.js code:

var server = require('http').Server(app);

After reading import and call a function with es6 I have tried the following:

import * as httpModule from 'http';
const server = httpModule.Server(app);

and the code does compile and run properly but I still get this TS error:

[ts] Property 'Server' does not exist on type 'typeof "http"'.

I have @types/node and @types/express installed. Am I missing something?

snowfrogdev
  • 5,963
  • 3
  • 31
  • 58
  • @Felix Kling I have edited my question and believe it is no longer a duplicate of https://stackoverflow.com/questions/31599566/import-and-call-a-function-with-es6 – snowfrogdev Jun 06 '17 at 14:10

1 Answers1

1

Try this:

import { Server, createServer } from 'http';
const server = createServer(app);

This might help.

Clarification: You are using default import instead named import.

Gurpreet Singh
  • 20,907
  • 5
  • 44
  • 60
  • This works, thank you. But I'd like to understand why it does and my solution doesn't. Also, why import `Server` from `http` if all we are using is `createServer`? Any insights? – snowfrogdev Jun 06 '17 at 18:02
  • Check out how imports work, you are mixing up default and named imports as updated in answer. – Gurpreet Singh Jun 07 '17 at 09:09
  • According to the TypeScript docs, using the `*`, like I did, doesn't import default exports but rather "imports the entire module into a single variable, and uses it to access the module exports". That's why I don't understand that it doesn't work. Technically it should. – snowfrogdev Jun 07 '17 at 12:03
  • Well I don't have node set up but you should be able to check/debug what 'httpModule' contains. – Gurpreet Singh Jun 07 '17 at 12:59