Node.js – Typescript: “Cannot find module” with valid typings

expressnode.jstypescripttypescript1.7

I just started a new nodejs project using typescript. I installed Typings (https://github.com/typings/typings) and used that to install reference files for node v4.x and express v4.x.

My node version is v4.2.6
My typescript version is v1.7.5

My project directory is laid out thus:

package.json
tsconfig.json
typings.json
src/
  app.ts
typings/
  main.d.ts
  main/ambient/node/node.d.ts
  main/ambient/express/express.d.ts

The contents of typings/main.d.ts are as follows:

/// <reference path="main/ambient/express/express.d.ts" />
/// <reference path="main/ambient/node/node.d.ts" />

The contents of tsconfig.json are as follows:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs"
  }
}

The contents off typings.json are as follows:

{
  "dependencies": {},
  "devDependencies": {},
  "ambientDependencies": {
    "express": "github:DefinitelyTyped/DefinitelyTyped/express/express.d.ts#dd4626a4e23ce8d6d175e0fe8244a99771c8c3f2",
    "node": "github:DefinitelyTyped/DefinitelyTyped/node/node.d.ts#1c56e368e17bb28ca57577250624ca5bd561aa81"
  }
}

The contents of src/app.ts are as follows:

'use strict';

///<reference path="../typings/main.d.ts"/>

import * as express from "express";

This is exceedingly simple and should result in a basic app. However, when I try to compile this I get the error error TS2307: Cannot find module 'express'.

I have tried rearranging typings files, changing the relative path in the reference path tag, using the files field in tsconfig.json to indicate the reference paths instead of using an inline tag in the file, all to no avail. I have also tried compiling using gulp-typescript, gulp-tsc, and tsc directly on the command line.

I get similar errors when I try to use nodejs build-in modules such as crypto, http, fs etc.

These references seem valid — what am I missing?

Best Solution

Triple-slash directives need to precede any statements in your file. Your "use strict" prologue needs to come after your reference comments as so:

///<reference path="../typings/main.d.ts"/>

'use strict';

import * as express from "express";

As a follow up to your comment where you're not getting any emit for your import: that's because TypeScript performs import elision. Unless you use the module for some value, the compiler won't emit the import because it assumes you only need that module for its types.

Related Question