使用带有TypeScript的npm模块 - 甚至无法使最简单的示例工作

时间:2015-09-18 22:08:37

标签: javascript node.js npm typescript

我想在Typescript程序中使用npm模块。幸运的是,我遇到了this这看起来非常简单,确实似乎有效。我想我会尝试添加另一个包,只是为了得到它的悬念。所以我forked it并制作了one relatively simple commit

这是我在提交中所做的所有事情:

  1. pubsub-js中为我的相关性添加了package.json,因此它将安装在npm install上。

  2. 设置tsd,用它来安装pubsub-js的TypeScript定义,并将其设置为自动在npm install上运行。

  3. 修改index.ts以包含已安装的定义:

    /// <reference path="./typings/pubsubjs/pubsub.d.ts" />
    

    并导入已安装的软件包:

    import PubSub = require('pubsub-js');
    
  4. 不幸的是,这不起作用。我收到这个错误:

    $ npm install
    $ npm test
    > demo-typescript-node-minimal@0.0.1 test /home/dumbmatter/projects/mini/demo-typescript-node-minimal
    > tsc index.ts --module commonjs && node ./index
    
    index.ts(10,25): error TS2307: Cannot find module 'pubsub-js'.
    npm ERR! Test failed.  See above for more details.
    

    (如果你想自己做,clone my repo,请运行npm install,然后npm test。)

    我想重申一下,原始版本(没有我的提交,直接来自the original repo)确实有效:

    $ git checkout d002c0dffc9d9f65aca465b0fc6a279bcd23202d
    $ npm test
    
    > demo-typescript-node-minimal@0.0.1 test /home/dumbmatter/projects/mini/demo-typescript-node-minimal
    > tsc index.ts --module commonjs; node ./index
    
    [ 'abc', index: 0, input: 'abcdefgh' ]
    Hello Dave
    

    那是什么给出的?为什么我的尝试失败如此悲惨?

    我也很感激任何有关在TypeScript中使用npm包的智慧的建议。是否只是容易出错才能真正使用?如果是这样,你发现自己处于你想要使用的TypeScript程序中的一些通用pubsub库的情况......你会怎么做?写你自己的?

1 个答案:

答案 0 :(得分:5)

问题是pubsub.d.ts不包含CommonJS模块"pubsub-js"的定义(而是仅定义全局对象PubSubJS)。

最好的解决方法是编辑该文件;在底部添加:

declare module "pubsub-js" {
  export = PubSub;
}

当CommonJS或AMD模块可用于给定包时,大多数.d.ts文件已包含此类定义。

相关问题