node.js 使用 TypeScript 导入节点模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18378503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Importing node-modules with TypeScript
提问by jorgenbs
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:
我正在尝试让它发挥作用,但我似乎无法在 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/');
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):
使用命令 "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.
回答by basarat
TypeScript needs to know that httpis present.
TypeScript 需要知道它http存在。
Updated
更新
Install the type definitinos for node:
为节点安装类型定义:
npm install @types/node
Old answer
旧答案
Follows these two steps
按照这两个步骤
- Download the
node.d.tsfile from here : https://github.com/borisyankov/DefinitelyTyped/tree/master/node At the top of your file add:
/// <reference path="node.d.ts" />
node.d.ts从这里下载文件:https: //github.com/borisyankov/DefinitelyTyped/tree/master/node在文件顶部添加:
/// <reference path="node.d.ts" />
PS: See a sample test file : https://github.com/borisyankov/DefinitelyTyped/blob/master/node/node-tests.ts
PS:查看示例测试文件:https: //github.com/borisyankov/DefinitelyTyped/blob/master/node/node-tests.ts
回答by Harvey
I found that I had noResolveset to truein my tsconfig.json file. This was causing errors with the references to the .d.ts files that I had included at the top of my TypeScript files.
我发现我已经在我的 tsconfig.json 文件中noResolve设置了true。这导致我在 TypeScript 文件顶部包含对 .d.ts 文件的引用出错。
回答by Alessandro L.
Shouldn't it be something like
不应该是这样的
/// <reference path="node.d.ts" />
import http = module('http')
I mean, shouldn't you use moduleinstead of require?
我的意思是,你不应该使用module代替require吗?

