繁体   English   中英

使用 TypeScript 导入节点模块

[英]Importing node-modules with TypeScript

我正在尝试让它发挥作用,但我似乎无法在 SO 上的任何地方找到解决方案。 尝试编译此单文件应用程序时:

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 标志会给我一个额外的错误,告诉我我需要它来编译外部模块):

error TS2071: Unable to resolve external module '"http"'.
error TS2072: Module cannot be aliased to a non-module type.

TypeScript 需要知道http存在。

更新

为节点安装类型定义:

npm install @types/node

旧答案

按照这两个步骤

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

我发现我的 tsconfig.json 文件中的noResolve设置为true 这导致我在 TypeScript 文件顶部包含对 .d.ts 文件的引用出错。

不应该是这样的

/// <reference path="node.d.ts" />
import http = module('http')

我的意思是,你不应该使用module而不是require吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM