我有一个用TypeScript编写的本地节点包,我想在我的实际项目中使用它。使用npm,我可以像这样安装本地包:
$ npm install --save /path/to/package或者:
$ npm install --save /path/to/package.tar.gz这将在node_modules目录中安装所需的.js文件。在该包中还有一个生成的.d.ts文件,我希望将其安装到我的项目中(在typings/tsd.ts中自动链接它)。但是使用以下命令没有任何效果:
$ tsd install /path/to/package/package.d.ts --save上面写的是>> zero results。那么,安装本地定义文件而不需要存储库的方法是什么呢?
更新:
我可以简单地将我的d.ts文件复制到typings目录和我的文本编辑器(对于我来说,它是带有TypeScript插件的Sublime文本),它能够找到声明。目录布局如下所示:
/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');但是,即使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;
}发布于 2016-01-03 04:55:46
在本地节点包中,在package.json中添加一个typescript > definition条目
{
"name": "your-package",
...
"typescript": {
"definition": "package.d.ts"
}
}然后,在项目中安装包后,运行命令...
tsd link...which将在项目的tsd.d.ts文件(reference)中添加对package.d.ts的引用。
另外,根据您的编辑,我建议您将定义文件更改为如下形式(请注意my-package周围的引号):
declare module "my-package" {
function myPackage(a: string, b: string): string;
export = myPackage;
}这将使它与以下代码一起工作:
import myPackage = require('my-package');
myPackage('foo', 'bar');发布于 2016-02-10 03:13:57
即使package.json的技巧是有效的,我还是更喜欢为此而设计的工具(tsd或类型)。
我刚刚找到了Typings的答案:
typings install --save --ambient file:./node_modules/.../file.d.ts
我认为tsd也是如此:)
编辑:
因为TypeScript 2.0类型是无用的。
只需运行npm i --save-dev @types/some-library
发布于 2016-01-03 11:15:11
从TypeScript 1.6开始,你可以从你的package.json中引用你的类型定义文件,并且TypeScript的模块解析应该能够挖掘出类型定义。
在(本地npm模块的) package.json文件中,添加一个“类型”条目,例如
{
"name": "my-package",
"typings": "./relative/path/to/my-package.d.ts"
}这样你就完全不需要摆弄TSD了。
请参阅TypeScript维基:https://github.com/Microsoft/TypeScript/wiki/Typings-for-npm-packages
https://stackoverflow.com/questions/34569659
复制相似问题