dcsan dcsan - 8 months ago 207
Node.js Question

How to use typescript with nodeJS - `require` problems

I'm setting up a new node/typescript project,
and having trouble getting the basics working.

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

Is giving me
error TS2304: Cannot find name 'require'.

So I think typings are needed? Tried:

typings install node
typings install nodejs
typings install require

All of which give

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

What is the correct way to get require, or any simple node app working with typescript.

TS is great once you get going, but the shifting sands around initial configuration are quite a hassle to get going.
I also looked at this answer, but it doesn't solve this issue. Some of the suggestions there no longer seem to work.

I'm trying to compile down to ES6.
typings version 1.0.5

Using a
and a
I have copied over from a separate working project and removed as much as possible. I guess I have to go through with tweezers and try to figure out what's different.


This book is quite helpful if you are trying to learn TypeScript and contains the following:

Add node.d.ts (typings install dt~node --global) to your compilation context. That's it! Now you can use all the built in node modules (e.g. import fs = require('fs'))

and also check out the documentation on the Typings repo.

In general, you can try, eg: typings search node

and you should see the available types and their source.

eg: node has sources under dt and env.

dt is short for the Definitely Typed repository. This is a large GitHub repository of community made type definitions, but now you have to specify if you want to install it from here. Normally, the best source is from npm because these are hopefully maintained by the core team of that repository.

You can also specify versions [<source>~]<pkg>[@<version>][#<tag>] where <version> A semver range (E.g. ">=5.0")

Use --global flag for ambient types.

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

For example, my typings.json had the following:

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