2
votes

I have a project that I based on the angular 2 seed repository (https://github.com/mgechev/angular2-seed) that I am trying to add an express server backend to written in TypeScript. My directory structure is identical, except I added a folder called server/ to src/.

I've run typings install and I can see that express.d.ts is in the typings/ directory, but for some reason when compiling my code I always get the following error (using [email protected]):

> npm start

> [email protected] start C:\Users\Cody\projects\angular2-seed
> tsc --outDir build/ --module commonjs ./src/server/server.ts && node ./build/server.js

src/server/server.ts(1,26): error TS2307: Cannot find module 'express'.

./src/server/server.ts:

import * as express from 'express';

let app = express();

app.get('/', function(req, res) {
  res.send('Hello World');
});

app.listen(3000, 'localhost');
console.log('Listening on port 3000');

Strangely enough the server runs without complaining if I use ts-node

> ts-node ./src/server/server.ts
Listening on port 3000

but I'm not going to use ts-node in production for fear of performance issues (not sure if that's justified or not).

Why can't the compiler find the express external module? I'm pretty new to using TypeScript so any help is appreciated.

** EDIT **

tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "declaration": false,
        "noImplicitAny": false,
        "removeComments": true,
        "noLib": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "sourceMap": true
    },
    "files": [
      "typings/main.d.ts"
    ],
    "exclude": [
        "node_modules",
        "typings/browser.d.ts",
        "typings/browser/**"
    ],
    "compileOnSave": false
}

The typings docs say that you only need to either exclude one or include the other, but I tried both and it still didn't work.

2

2 Answers

1
votes

but I'm not going to use ts-node in production for fear of performance issues (not sure if that's justified or not).

Justified. Though only slightly. Its just an initial compile cost you are saving.

Why can't the compiler find the express external module?

Make sure your tsconfig.json is setup correctly to include typings/main.d.ts 🌹

0
votes

It turns out the version of the typescript compiler I was using was not the one I had installed through npm, but was installed through Visual Studio and was old (version 1.0). You can check this by running where tsc.

The solution was to remove theC:\Program Files (x86)\Microsoft SDKs\TypeScript 1.0 entry from my Path env variable.

According to this GItHub issue, it looks like this is the official accepted solution.