使用 TypeScript 导入节点模块

2023-12-21

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

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存在。

Updated

安装节点的类型定义:

npm install @types/node

旧答案

遵循以下两个步骤

  • 下载node.d.ts来自这里的文件:https://github.com/borisyankov/DefinitelyTyped/tree/master/node https://github.com/borisyankov/DefinitelyTyped/tree/master/node
  • 在文件顶部添加:

    /// <reference path="node.d.ts" />
    

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 TypeScript 导入节点模块 的相关文章

随机推荐