简体   繁体   English

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

[英]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: 假设我已经编写了一个名为get-subject的npm包,其源代码为src/index.ts如下所示:

import { ReplaySubject } from 'rx';

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

I have package.json: 我有package.json:

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

And tsconfig.json: 和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/ : 现在我运行tsc -d并在lib/生成文件:

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

And lib/index.d.ts looks like lib/index.d.ts看起来像

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

Time to use npm package "get-subject" as a dependency 是时候使用npm包“get-subject”作为依赖

Do normal npm i . 做正常的npm i Wrote some code using get-subject package: 使用get-subject包写了一些代码:

import getSubject from 'ts-npm-package';

getSubject()

But when I run tsc , it tells me: 但是当我运行tsc ,它会告诉我:

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. 如果我在tsconfig.json的files属性中包含node_modules/rx/ts/rx.all.d.ts (我使用npm @ 3,因此Rx依赖关系不嵌套在get-subject )。 tsc will work. tsc会起作用。 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. 直到rx.js附带了.d.ts文件是紧挨.js文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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