3
votes

I am building a typescript module that I am going to share between a node server and an angular2 app, but require doesn't seem to be able to find it after it is installed. Here is my shared module

package.json

{
  "name": "MyCommonLibrary",
  "version": "0.0.1",
  "description": "",
  "main": "bin/index.js",
  "scripts": {
  },
  "license": "ISC",
  "devDependencies": {
    "typescript": "^1.8.9",
    "typings": "^0.7.9"
  }
}

tsconfig.json

{
    "compilerOptions":{
        "target":"es5",
        "module":"commonjs",
        "declaration":true,
        "sourceMap":true,
        "sourceRoot":"src",
        "outDir":"bin"
    },
    "exclude":[
        "node_modules",
        "bin",
        "typings/main",
        "typings/main.d.ts"
    ]
}

src/index.ts

export class TestClass {
    name:string;
    constructor(name:string){
        this.name = name;
    }
}

Everything seems to compile properly, my bin/index.js looks good. I run

"npm install ../MyCommonLibrary --save"

from the server project and the module installs correctly. But then I get an error when I try to compile,

cannot find module 'MyCommonLibrary'

Even though the MyCommonLibrary exists in the node_modules directory and seems to have all the proper information

server.ts

import express = require('express');
import myCommonLibrary = require('MyCommonLibrary');
var app = express();

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

var server = app.listen(3000,function(){
    var host:string = server.address().address;
    var port:number = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);
});

Any insight would be appreciated

EDIT: After doing a lot of digging I wound up finding a solution! From this example I found that adding

"typings":"bin/index",

To my package.json fixes the issue, even though the Atom Typescript plugin still complains, tsc compiles just fine.

Can you check by setting the moduleResolution property to node in your tsconfig.json (compilerOptions) ? - Fidan Hakaj
Setting the moduleResolution to node fixes the issue I was having with the Atom typescript plugin, but does not fix the compile issue oddly enough. Adding the typings options to package.json fixed the compile issue. - Nevorious
Has been answered in this other S/O question - Offirmo