Reputation: 4545
The simple question here is how do I use namespaced typescript classes as external modules for use in node. The answer to that seems to be
It can't be done, don't try it, don't use namespaces
Well I am in the position that we have a large codebase that is all written in namespaces and we are now trying to use this code in node.js as well.
I am trying to figure out how to use our existing code.
I have got as far as compiling my namespaced code into a commonjs nodelibs folder that produces one js
file and one d.ts
for each ts
file.
I have to add the following to each of my ts files that I want to be available to node:
namespace Organisation.Project.Entities{
export class SomeThing{
}
}
var module: {copy module definition from node.d.ts}
if(module)
{
module.exports = Organisation.Project.Entities;
}
I can use this code in my node application:
var entities = require("../nodelibs/entities/entities");
var myThing = new entities.SomeClass();
despite there being both a entities.js
and entities.d.ts
at ../nodelibs/entities/entities
there is no type info or compile time checking that SomeClass
is a thing.
I can manually import the references file and manually type the instance of the class but in my case SomeClass
is a class with a lot of statics on it so I can't fingure out how to type it properly...
var entities = require("../nodelibs/entities/entities");
var classRef = entities.SomeClass;
var myVar = classRef.staticProperty;
In this example I can't type classRef
as SomeClass
as it isn't an instance of SomeClass
, it's the class constructor.
How do I type classRef so that I can get access to the static properties on the class Some Class
?
Thanks
Upvotes: 0
Views: 627
Reputation: 23742
In the module, use the static ES6 module syntax:
// File entities.ts
export namespace Organisation.Project.Entities {
export class SomeClass {
public static abc = 'abc';
}
}
Then, import your namespace:
// File main.ts
import {Organisation} from './entities';
type classRef = Organisation.Project.Entities.SomeClass;
var myVar = classRef.abc;
Say the compiler to generate modules in the CommonJS format:
// File tsconfig.json
{
"compilerOptions": {
"module": "commonjs"
},
"exclude": [
"node_modules"
]
}
In a browser, you can use a bundler or a loader. There is some configuration to do.
Bundlers:
Loaders:
Upvotes: 1