【发布时间】:2016-04-06 19:07:49
【问题描述】:
我有一个用 TypeScript 编写的本地节点包,我想在我的实际项目中使用它。使用 npm,我可以像这样安装本地包:
$ npm install --save /path/to/package
或者:
$ npm install --save /path/to/package.tar.gz
这会在 node_modules 目录中安装所需的 .js 文件。该包中还有一个生成的 .d.ts 文件,我想将其安装到我的项目中(自动将其链接到 typings/tsd.d.ts)。但是使用下面的命令没有效果:
$ tsd install /path/to/package/package.d.ts --save
上面写着>> zero results。那么,在不需要存储库的情况下,安装本地定义文件的方法是什么?
更新:
我可以简单地将我的 d.ts 文件复制到类型目录和我的文本编辑器(对我来说它是带有 TypeScript 插件的 Sublime Text)它能够找到声明。目录布局是这样的:
/my-project/
/typings/
tsd.d.ts - auto-generated by `tsd install`
node/ - I've installed the node definitions
my-package.d.ts - copied or symlinked file
my-project.ts - I'm working here
但是,在导出 module.exports(TypeScript 中的 exports = function...)中的唯一函数时,我遇到了问题。在这种情况下,导出的函数有点“匿名”,甚至没有在 d.ts 文件中命名,所以我需要手动编辑它。
我的测试用例:
'my-package' 提供单一功能,通常导入为'myPackage':
export = function myPackage(a: string, b: string) { return a + ' ' + b; };
declaration在tsconfig.json中设置为true,所以tsc命令生成了一个my-package.d.ts文件:
declare var _default: (a: string, b: string) => string;
export = _default;
我的包应该在我的项目中这样使用:
import myPackage = require('my-package');
myPackage('foo', 'bar');
但是,tsc 找不到 myPackage,即使 my-package.d.ts 已复制到类型文件夹中。我需要编辑该文件,使其看起来像这样:
declare var myPackage: (a: string, b: string) => string;
//export = _default; - not needed
对于正确运行的require(),甚至更好:
declare module 'my-package' /* this is the string passed to require() */ {
export = function(a: string, b: string): string;
}
【问题讨论】:
-
从 node_modules 导入 d.ts 文件(我只是在那里复制了一个文件)对我来说似乎工作得很好,不需要 tsd 做任何事情。
-
你说得对,toskv,我可以简单地复制 d.ts 文件,而不需要在 typings/tsd.d.ts 中引用它。如果我设置了 exports 变量,我遇到了一个问题,我已经更新了我的帖子,提供了更多关于此的信息。
标签: typescript definitelytyped tsd