In TypeScript I can define a global/top-level namespace and use it in another file like so:
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 foo.blah.baz()
call in the other file fails. export namespace ...
just causes the namespace to become part of the module's export, not a global.
Is there a way to write a TypeScript file which imports from other modules but also defines global/top-level symbols?
At the moment I'm 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 can't see that foo.blah...
exists as a global in other files.
(The file is the entry point for Webpack, and I'm trying to import things from other modules in the Webpack bundle and assign them to globals so they can be used in <script>
tags on the page.)
To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.
Namespace Declaration We can create a namespace by using the namespace keyword followed by the namespace_name. All the interfaces, classes, functions, and variables can be defined in the curly braces{} by using the export keyword. The export keyword makes each component accessible to outside the namespaces.
To use it, it must be included using triple slash reference syntax e.g. ///<reference path="path to namespace file" /> . Must import it first in order to use it elsewhere. Compile using the --outFile command. Compile using the --module command.
When you add the import
, you switch from internal modules to external ones, as the spec says:
In external modules, relationships between files are specified in terms of imports and exports at the file level. In TypeScript, any file containing a top-level import or export is considered an external module.
http://www.typescriptlang.org/Handbook#modules-going-external
The philosophy behind external modules is to avoid global objects, why don't you create a new module with foo.blah
(and all the stuff you need) and import it as TypeScript expects it?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With