我有一个用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文件复制到typings目录和我的文本编辑器(对我来说,它是使用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...
)中的唯一函数时出现问题 . 在这种情况下,导出的函数有点'anonymous',甚至在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');
但是,即使将 my-package.d.ts
复制到typings文件夹中,tsc也找不到 myPackage
. 我需要编辑该文件,使其看起来像这样:
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;
}
3 回答
在本地节点包中,在
package.json
中添加typescript > definition
条目:然后在项目中安装包后,运行命令...
...将在项目的
tsd.d.ts
文件(reference)中添加对package.d.ts
的引用 .此外,根据您的编辑,我建议您将定义文件更改为这样的(注意
my-package
周围的引号):这将使它与以下代码一起使用:
即使package.json的技巧有效,我也更喜欢为此制作的工具(tsd或typings) .
我刚刚找到了打字的答案:
typings install --save --ambient file:./node_modules/.../file.d.ts
我觉得和tsd一样:)
EDIT:
因为TypeScript 2.0打字是没用的 .
跑吧
npm i --save-dev @types/some-library
从TypeScript 1.6开始,您可以从package.json引用类型定义文件,TypeScript的模块分辨率应该能够挖掘出类型定义 .
在你的package.json文件中(你的本地npm模块),添加一个“typings”条目,例如
这样你根本不需要摆弄TSD .
参见TypeScript Wiki:https://github.com/Microsoft/TypeScript/wiki/Typings-for-npm-packages