简体   繁体   中英

How to create typings declaration for javascript module exported as a global?

I wrote a library written in typescript and I use webpack to bundle it into a single, minified js file that exports the library as one global variable. I want to distribute these typings for the developers on my team. They are not typescript users so they would be importing the library itself via a <script src="..."> tag and they would import the typings using the triple slash reference directive /// <reference path="..." /> or typings or something similar.

The question is then:

How do I enable typings (ie, the intellisense) for my library for the js developers that use vs code? How do I declare that there is one global variable that exports the values that my entry point does?

I have enabled the declarationDir and declartion compiler options to create create the declaration files ( *.d.ts ) for all my typescript source files but these declarations don't declare that there is a global variable available with the methods.

I've tried manually creating a index.d.ts declaration in the same folder where the bundle and minified index.js file is but I can't get it to work.

Here is what I tried:

import * as myModule from './typings/src/';

declare module TheGlobalVariable {
    // how do I declare that `TheGlobalVariable` has the same methods
    // as `myModule` exports?
    export = myModule; // doesn't work
}

where ./typings/src/index.d.ts is the generated declaration file for the entry point of this library and TheGlobalVariable is the name of the global variables webpack exports.

Any ideas?

Oh I figured it out.

In the same folder where my bundled js library file is ( index.js ), I added a file index.d.ts . Here is that file:

export * from './src';
export as namespace OntologyStore;

The key enabler is the export as ... .

Refer to this module template and this documentation on library structures .

Also change the webpack libraryTarget to 'umd' . UMD modules check to see if there is a module loader and if there isn't it will export to a global. Also I didn't have to use the declaration or declarationDir compiler options.

Use this structure, https://github.com/botika/typescript-package . Only follow a README.md

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