简体   繁体   English

将程序包发布到NPM时,如何包含额外的Typescript声明?

[英]How do I include extra Typescript declarations when I publish my package to NPM?

I'm writing a Typescript package that will be published on NPM, and I'd like to include some custom declarations along with the main declaration file that's generated by the Typescript compiler. 我正在写一个将在NPM上发布的Typescript包,我想包括一些自定义声明以及Typescript编译器生成的主声明文件。 However, when I install my package as a dependency in another project, Typescript only recognizes the generated declaration file, not the extra ones that I also want included in my project. 但是,当我将软件包作为依赖项安装在另一个项目中时,Typescript仅识别生成的声明文件,而不识别我也希望包含在项目中的多余文件。

For example, assuming my package is called "my-package": 例如,假设我的包裹被称为“ my-package”:

//In typings/my-interface.d.ts

declare module "my-package/interfaces" {
    export interface MyInterface { ... }
} 

I can use that declaration throughout the original package without any problems by importing it with import { MyInterface } from "my-package/interfaces" . 通过import { MyInterface } from "my-package/interfaces"使用import { MyInterface } from "my-package/interfaces"该声明,可以在整个原始包中使用该声明,而不会出现任何问题。 The problem is Typescript can't find "my-package/interfaces" when the package is installed as a dependency in another project. 问题是当该软件包作为依赖项安装在另一个项目中时,Typescript找不到"my-package/interfaces" It only knows about "my-package" , even when the custom declarations are included in the package, and even when they're referenced from the compiled declaration. 即使自定义声明包含在包中,甚至从编译的声明中引用它们,它也只知道"my-package"

As a real-world example, assume that lodash was written in Typescript and the author wanted to include declarations for all of the cherry-picked functions, along with the main lodash declaration file: 作为一个真实的例子,假设lodash是用Typescript编写的,而作者想包括所有摘自樱桃的函数的声明以及主要的lodash声明文件:

declare module "lodash/some" {
    export function ...
}

declare module "lodash/forOwn" {
    export function ...
}

Is it possible to include my custom declarations in an NPM package and have Typescript pick them up along with the compiled declaration? 是否可以将我的自定义声明包含在NPM包中,并让Typescript连同编译的声明一起将它们拾取?

The easiest way I can think of is to not name your custom declaration file using "d.ts" but keep it to just declarations. 我能想到的最简单的方法是不使用“ d.ts”命名自定义声明文件,而仅将其保留为声明。

For example, try renaming my-interface.d.ts to my-interface.ts . 例如,尝试将my-interface.d.ts重命名为my-interface.ts When you compile tsc will generate my-interface.d.ts for you and you should be able to use it fine upstream. 编译tsc时,将为您生成my-interface.d.ts ,您应该可以在上游正常使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM