简体   繁体   中英

Correct way to package ambient module in typescript for npm

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?

But this is the ideal solution?

Yes. Until rx.js ships with its .d.ts files being right next to its .js files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM