Define a global namespace / variable in a TypeScript module

In TypeScript, I can define a global / top-level namespace and use it in another file as follows:

namespace foo.blah { export function baz() { console.log('hello'); } } 

And in another file this works:

 foo.blah.baz(); 

However, if I then import something from another module:

 import Thing from 'boo'; namespace foo.blah { export function baz() { console.log('hello'); } } 

Suddenly my whole file is a module, the foo.blah namespace is local, not global, and the call to foo.blah.baz() in another file fails. export namespace ... just makes the namespace become part of the module export, not global.

Is there a way to write a TypeScript file that imports from other modules, but also defines global / top-level characters?

I am currently doing this:

 import Thing from 'boo'; import * as $ from 'jquery'; namespace foo.blah { export function baz() { console.log('hello'); } } $.extend(true, window, {foo}); 

Which works, but the TypeScript compiler still cannot see that foo.blah... exists as global in other files.

(The file is the entry point for Webpack, and I'm trying to import things from other modules into the Webpack package and assign them global so that they can be used in the <script> tags on the page.)

+5
source share
1 answer

When you add import , you switch from internal to external modules, as the specification says:

In external modules, the relationships between files are specified in the import and export conditions at the file level. In TypeScript, any file containing top-level import or export is considered an external module.

http://www.typescriptlang.org/Handbook#modules-going-external

The philosophy of external modules is to avoid global objects, why don't you create a new module with foo.blah (and all you need) and import it as TypeScript expects it?

+2
source

Source: https://habr.com/ru/post/1236592/


All Articles