To create classes at the module/namespace level and instantiate objects of them when needed, you can follow this approach:
export class MyClass {}
loadDependency(function(dep) {
let myInstance = new MyClass();
// do something with myInstance, MyClass, and dep
});
This way, you will have access to MyClass
from other files as well.
The reason why exporting in your example doesn't work is because export
only functions within the module or namespace context. It's a static declaration that specifies the availability of the class outside the module or namespace.
For instance, this:
export class MyClass {}
translates to:
define(["require", "exports"], function (require, exports) {
"use strict";
var MyClass = (function () {
function MyClass() {
}
return MyClass;
}());
exports.MyClass = MyClass;
});
Similarly, this:
module moo {
export class MyClass {}
}
Gets converted to:
var moo;
(function (moo) {
var MyClass = (function () {
function MyClass() {
}
return MyClass;
}());
moo.MyClass = MyClass;
})(moo || (moo = {}));
(assuming target ES5
and default module system is CommonJS
).
If you require the dep
inside the class, pass it as a parameter to the constructor like this:
export class MyClass {
private dep: any;
constructor(dep: any) {
this.dep = dep;
}
myF() {
this.dep.myStuff();
}
}
loadDependency(function(dep) {
let myInstance = new MyClass(dep);
});
In conclusion, ensure the proper scope while defining classes for successful access across different modules.