使用TypeScript导入节点模块 [英] Importing node-modules with TypeScript

查看:206
本文介绍了使用TypeScript导入节点模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使其正常工作,但是我似乎无法在SO的任何地方找到解决方案.尝试编译此单文件应用程序时:

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/');

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

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.

推荐答案

TypeScript需要知道http存在.

TypeScript needs to know that http is present.

为节点安装类型definitinos:

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:请参阅示例测试文件: https://github.com/borisyankov/DefinitelyTyped/blob/master/node/node-tests.ts

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

这篇关于使用TypeScript导入节点模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆