【问题标题】:Using npm modules with TypeScript - can't even get the simplest example working使用带有 TypeScript 的 npm 模块 - 甚至无法让最简单的示例正常工作
【发布时间】:2015-12-16 04:16:03
【问题描述】:

我想在 Typescript 程序中使用 npm 模块。幸运的是,我遇到了this,它看起来很简单,而且似乎确实有效。我想我会尝试添加另一个包,只是为了掌握它。所以我forked itone 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');
    

很遗憾,这不起作用。我收到此错误:

$ 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 库……您会怎么做?自己写?

【问题讨论】:

    标签: javascript node.js npm typescript


    【解决方案1】:

    问题在于 pubsub.d.ts 不包含 CommonJS 模块 "pubsub-js" 的定义(相反,它只定义了一个全局对象 PubSubJS)。

    最好的解决办法是编辑那个文件;在底部添加:

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

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

    【讨论】:

    • 该死,你回答得这么快,Stack Overflow 还不让我接受!
    猜你喜欢
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多