James Moorhouse
James Moorhouse

Reputation: 183

Typescript 2 can't find custom definitions

I'm trying to use some external js libraries from NPM with my typescript project, unfortunately these libraries don't have @types definitions provided so I've taken to writing my own. The definitions I've written work when I nest them in ./node_modules/@types/<library_name>/*.d.ts but as soon as I move them to e.g. ./@types/<library_name>/*.d.ts they don't get picked up by the compiler and I get the following error:

ERROR in ./utils/eventEmitter.ts
(1,25): error TS2307: Cannot find module 'events'.

I'm using: TypeScript Version: 2.0.3 from npm

I've got the following project structure setup

@types/
-- events
---- index.d.ts
node_modules/
-- @types
-----react, react-dom etc
utils/
-- eventEmitter.js
tsconfig.json

In my tsconfig.json I have:

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "sourceMap": true,
    "typeRoots" : [
      "./@types"
    ],
    "types" : [
      "events",
      "ajax",
      "path",
      "keymirror"
    ]
  },
  "exclude" : [
    "node_modules",
    "@types"
  ]
}

in eventEmitter.js I have the following:

import * as events from "events";

Just to clarify the concrete events module JS is located at ./node_modules/events/index.js

Upvotes: 4

Views: 2395

Answers (3)

James Moorhouse
James Moorhouse

Reputation: 183

The problem described by my question has been acknowledged as a bug in typescript (I'm using 2.0.3).

The solution is to add the following config to tsconfig.json:

{
"compilerOptions": {
    ...
    "paths": {
         "*": ["*", "./@types/*"]
     }
     ...
  }
}

as per: github issue

Upvotes: 3

Yakov Fain
Yakov Fain

Reputation: 12376

You can keep your file definition file in the root dir of your project and tsc will find it.

Upvotes: 0

Kacper Polak
Kacper Polak

Reputation: 1411

Please use it this way:

import * as events from "./events";

When you use

 import * as events from "events";

typescript search for it in node_modules, you need to give him relative path with ./

Upvotes: 0

Related Questions