Zoltán Tamási
Zoltán Tamási

Reputation: 12754

How to use a typing which provides an external module as global?

We have a large TS application mostly written way before 2.0. We are not using modules, but only the outfile option. We've been using global typings so far, but now some of the typings provided by typings are not supporting global usage (as far as I understand).

For example I'm now trying to use the typings for markdown-it, which doesn't expose anythings to the global namespace, hence the compiler doesn't find the markdownit function.

I'm quite confused about how we should use these kind of typings in these circumstances, any hints would be appreciated.

Example code:

// test.ts
var result = markdownit().render("*some markdown*"); <-- `markdownit` not found

When I try to import it, it gives error of course, because I'm not using modules. So I'm stuck.

Upvotes: 0

Views: 306

Answers (1)

artem
artem

Reputation: 51579

Assuming you really want to use markdown-it as global variable markdownit, you can declare it in your own file that augments global scope (this feature is new in 2.0).

Create a file markdown-it-global.d.ts

declare module 'markdown-it-global' {

    import * as MarkdownIt from 'markdown-it';

    global {
        var markdownit: typeof MarkdownIt;
    }

}

This declares an ambient module that augments global scope - if you include markdown-it-global.d.ts together with all other typecsript source files and declarations like typing/index.d.ts, it will make global variable markdownit available everywhere.

The import inside it uses markdown-it typings that declare a module, but it will be used for typechecking only, it will not have any effect on generated javascript code and will not actually require it to use modules.

Upvotes: 1

Related Questions