在 npm 的打字稿中打包环境模块的正确方法

Correct way to package ambient module in typescript for npm

假设我写了一个名为 get-subject 的 npm 包,来源 src/index.ts 如下所示:

import { ReplaySubject } from 'rx';

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

我有 package.json:

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

和tsconfig.json:

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

现在我 运行 tsc -d 并且它在 lib/:

中生成文件
lib/index.js
lib/index.d.ts

而且lib/index.d.ts看起来像

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

是时候使用 npm 包 "get-subject" 作为依赖项了

做正常 npm i。使用 get-subject 包编写了一些代码:

import getSubject from 'ts-npm-package';

getSubject()

但是当我运行tsc时,它告诉我:

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

如果我在 files 属性 中包含 node_modules/rx/ts/rx.all.d.ts(我使用 npm@3 所以 Rx 依赖项没有嵌套在 get-subject 下) 属性 . tsc 会起作用。 但这是理想的解决方案吗?我可以提供一种方法,让软件包用户不必自己弄清楚缺少什么吗?

But this is the ideal solution?

是的。直到 rx.js 附带它的 .d.ts 文件 右边 在它的 .js 文件旁边。