Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing node-modules with TypeScript

I'm trying to get this to work, but I can't seem to find a solution anywhere on SO. When trying to compile this single-file app:

import http = require('http') http.createServer(function (req, res) {   res.writeHead(200, {'Content-Type': 'text/plain'});   res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); 

Using the command "tsc app.ts --module 'commonjs'" I get the following error (not using the --module flag gives me an additional error telling me that I need it to compile external modules):

error TS2071: Unable to resolve external module '"http"'. error TS2072: Module cannot be aliased to a non-module type. 
like image 405
jorgenbs Avatar asked Aug 22 '13 10:08

jorgenbs


People also ask

How do I import a custom module in TypeScript?

Approach: Before importing any module we need to export it from another file. We can create a module by using the export keyword and can use it in other modules by using the import keyword. We can export both class-based modules and function-based modules. as shown below.

How do I import all modules into a directory in TypeScript?

To import all modules from a directory in TypeScript, we can create a module that reexports all modules that were imported. export { default as A } from "./a"; export { default as B } from "./b"; to import the default exports from modules a and b .

Can I use import in TypeScript?

Importing Types With TypeScript 3.8, you can import a type using the import statement, or using import type .


1 Answers

TypeScript needs to know that http is present.

Updated

Install the type definitinos for node:

npm install @types/node 

Old answer

Follows these two steps

  • Download the node.d.ts file from here : https://github.com/borisyankov/DefinitelyTyped/tree/master/node
  • At the top of your file add:

    /// <reference path="node.d.ts" /> 

PS: See a sample test file : https://github.com/borisyankov/DefinitelyTyped/blob/master/node/node-tests.ts

like image 158
basarat Avatar answered Oct 08 '22 18:10

basarat