简体   繁体   中英

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. 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.

For example, assuming my package is called "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" . The problem is Typescript can't find "my-package/interfaces" when the package is installed as a dependency in another project. 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.

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:

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?

The easiest way I can think of is to not name your custom declaration file using "d.ts" but keep it to just declarations.

For example, try renaming my-interface.d.ts to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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