I used typescript in the past mainly for client side code to run in the browser. Now I am trying to reuse some classes of my library for node.js. My setup looks like this:
- SharedLibrary Project with multiple classes
- Client Project using the SharedLibrary
- Server Project with node.js using the SharedLibrary
Node.js seems to force me to use commonjs as module library for typescript. Thus my code on the server side will be forced to use modules as well. How can I include my SharedLibrary now in this project? It seems modules are unable to access anything outside of the module except if it is itself a module but I also can't change my SharedLibrary to a module as this would force me to change my whole code base. Is there any way out of this without having to change everything?
Example code: Library file A.ts:
class A {
public call() {
console.log("class A");
}
}
Server file C.ts:
export class C {
public call(): void {
console.log("class c");
let a = new A(); //this will compile but crash during runtime
a.call();
}
}
node.js main file:
import * as myodule from "./C";
var s = new myodule.C();
s.call();
It will print "class c" and then crash as it can't find class A. It works just fine if I add export to "class A" and then import it but then my client side code stops working.
What I tried so far:
- using the files directly doesn't work
- using the export keyword to export class A outside of its .ts file doesn't seem to work either
- C style defines might work that optionally define the shared library as export or not should work but I couldn't find anything like that in typescript