使用TypeScript导入节点模块

jor*_*nbs 34 node.js typescript

我试图让这个工作,但我似乎无法在任何地方找到解决方案.尝试编译此单文件应用程序时:

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/');
Run Code Online (Sandbox Code Playgroud)

使用命令"tsc app.ts --module'commonjs'"我得到以下错误(不使用--module标志给我一个额外的错误告诉我,我需要它来编译外部模块):

error TS2071: Unable to resolve external module '"http"'.
error TS2072: Module cannot be aliased to a non-module type.
Run Code Online (Sandbox Code Playgroud)

bas*_*rat 41

TypeScript需要知道它http存在.

更新

为节点安装类型definitinos:

npm install @types/node
Run Code Online (Sandbox Code Playgroud)

老答案

遵循这两个步骤

PS:查看示例测试文件:https://github.com/borisyankov/DefinitelyTyped/blob/master/node/node-tests.ts

  • 所有到Github的链接都被破坏了.这个答案仍然有效吗? (4认同)