使用 TypeScript 导入节点模块 [英] Importing node-modules with 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
');
}).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.
为节点安装类型定义:
npm install @types/node
旧答案
按照这两个步骤
- 从这里下载
node.d.ts
文件:https://github.com/borisyankov/DefinitelyTyped/tree/master/node 在文件顶部添加:
- 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屋!