gpt4 book ai didi

typescript - tsd:安装本地定义文件

转载 作者:搜寻专家 更新时间:2023-10-30 20:41:37 25 4
gpt4 key购买 nike

我有一个用 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

它说 >> 零结果。那么,在不需要仓库的情况下安装本地定义文件的方法是什么?

更新:

我可以简单地将我的 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...)时,我遇到了问题。在这种情况下,导出的函数有点“匿名”,甚至没有在 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 已被复制到 typings 文件夹中。我需要编辑该文件,使其看起来像这样:

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;
}

最佳答案

即使 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

关于typescript - tsd:安装本地定义文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34569659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com