如何在 nodeJS 中使用 typescript - `require` 问题

How to use typescript with nodeJS - `require` problems

我正在建立一个新的 node/typescript 项目, 并且无法使基础知识发挥作用。

'use strict';
let fetch = require("node-fetch");

给我error TS2304: Cannot find name 'require'.

所以我认为需要打字?尝试过:

typings install node
typings install nodejs
typings install require

全部给

Unable to find "XXX" ("npm") in the registry

获取 require 或使用 typescript 的任何简单节点应用程序的正确方法是什么。

一旦开始,TS 就很棒,但是围绕初始配置的流沙让开始变得非常麻烦。 我也是,但是没有解决这个问题。那里的一些建议似乎不再有效。

我正在尝试编译为 ES6。 打字版本 1.0.5

使用 tsconfig.jsontypings.json 我从一个单独的工作项目中复制过来并尽可能多地删除。我想我必须用镊子仔细检查并尝试找出不同之处。

TypeScript 2+ 支持:

npm install --save @types/node

打字:

typings install dt~node --global

并查看 Typings repo 上的文档。

一般情况下,你可以试试,eg: typings search node

您应该会看到可用的类型及其 source

例如:nodedtenv 下有来源。

dt 是 Definitely Typed 存储库的缩写。这是一个大型的 GitHub 社区类型定义存储库,但现在您必须指定是否要从此处安装它。通常,最好的来源是 npm,因为它们有望由该存储库的核心团队维护。

您还可以指定版本 [<source>~]<pkg>[@<version>][#<tag>] where <version> A semver range (E.g. ">=5.0")

对环境类型使用 --global 标志。

Global is the new ambient:

Usages of ambient are now global

That means in typings.json any ambientDependencies should be renamed globalDependencies and any ambientDevDependencies should be renamed globalDevDependencies.

It also means --ambient is now --global

例如,我的 typings.json 有以下内容:

globalDependencies": {
  "node": "registry:dt/node#6.0.0+20160523035754",

对于那些只想知道如何摆脱困境的人,请使用:

typings install dt~node --global