2015-09-18 36 views
0

我想在Typescript程序中使用npm模塊。幸運的是,我碰到了this,看起來很容易,而且確實似乎工作。我想我會嘗試添加另一個包,只是爲了獲得它的竅門。所以我forked itone relatively simple commit在TypeScript中使用npm模塊 - 甚至無法獲得最簡單的例子

這裏就是我在做的事情我承諾:

  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'); 
    

不幸的是,這是行不通的。我得到這個錯誤:

$ npm install 
$ npm test 
> [email protected] 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 

> [email protected] 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庫的情況下,您正在使用......您將如何操作?寫你自己的?

回答

5

問題是pubsub.d.ts不包含CommonJS模塊的定義"pubsub-js"(而是它只定義了全局對象PubSubJS)。

最好的修復方法是編輯該文件;在底部添加:

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

大多數.d.ts文件已經包括了這樣的定義,當一個CommonJS的或AMD模塊可用於給定的包。

+0

該死的,你的回答太快了,Stack Overflow不會讓我接受它! – dumbmatter

相關問題