Correct way to package ambient module in typescript for npm

Viewed 604

Assuming I have wrote a npm package called get-subject with source src/index.ts like this:

import { ReplaySubject } from 'rx';

export default function getSubject() {
  return new ReplaySubject(1);
}

I have package.json:

"main": "lib/index.js",
"typings": "lib/index.d.ts",

And tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "moduleResolution": "node",
        "target": "es5",
        "outDir": "lib"
    },
    "files": [
      "src/index.ts",
      "node_modules/rx/ts/rx.all.d.ts"
    ]
}

Now I run tsc -d and it generates files in lib/:

lib/index.js
lib/index.d.ts

And lib/index.d.ts looks like

import { ReplaySubject } from 'rx';
export default function getSubject(): ReplaySubject<{}>;

Time to use npm package "get-subject" as a dependency

Do normal npm i. Wrote some code using get-subject package:

import getSubject from 'ts-npm-package';

getSubject()

But when I run tsc, it tells me:

node_modules/get-subject/lib/index.d.ts(1,31): error TS2307: Cannot find module 'rx'.

If I include node_modules/rx/ts/rx.all.d.ts (I use npm@3 so the Rx dependency is not nested under get-subject) in files property in tsconfig.json. tsc will work. But this is the ideal solution? Could I provide a way so that package user won't have to figure out what's missing by themselves?

1 Answers
Related