简体   繁体   中英

How do I reference a type declared in a TypeScript .d.ts file generated by tsc's “declaration” option in NPM package?

Big picture: my organisation has several Angular applications written in TypeScript, each of which contain a lot of duplicated code. We have started down a path of packaging our reusable TypeScript code as NPM packages and publishing them to the private NPM registry in TFS 2017. We are using Gulp to compile the reusable TypeScript code to JavaScript (with gulp-typescript) and using the "declarations" property in tsconfig.json to force a .d.ts file to be generated. This works, and the .d.ts file is included alongside the JavaScript output in the NPM package which gets installed in the client app. However, referencing the types within it in the consuming application doesn't work unless I put a reference to the .d.ts file directly in the consuming application, which I'd like to avoid.

We are using TypeScript 2.5 with the @types method for accessing third party typings, so for example with Angular I have "@types/angular": "1.6.32" in the package.json file - that causes node_modules\\@types\\angular\\index.d.ts to come into existence, and Visual Studio seems to magically discover that file provide strong type checking when I type ng.IServiceProvider in a TypeScript file.

It doesn't however magically discover my own Typings file which is located at node_modules\\my-package\\dist\\my-package.d.ts. However, if I add this to a TypeScript file:

/// <reference path="../../../node_modules/my-package/dist/my-package.d.ts" />

Then I can reference the types defined in the file. However, this is not a great solution as it means every consuming application needs to know the path within the node_modules folder to every custom Typings file I have created. Presumably this is what the @types syntax was supposed to help avoid.

Is there a way to make the consuming project magically discover custom typings files that are contained within an NPM package (as opposed to typings files that are published as packages in their own right?) I know I could do the latter, but I really don't want to have to create a separate @types package for every custom NPM package we create if I can avoid it.

I found a way to make this work:

{
    "name": "my-package",
    "main": "./dist/my-package.js",
    "types": "./dist/my-package.d.ts"
}

In the package.json file for the NPM package you need to add the reference to the bundled types package as shown above. That makes Visual Studio pick up the reference and provide intellisense for the types included in the package.

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