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:
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:
Is there any way out of this without having to change everything?
Just use commonjs everywhere and use a module loader/bundler like webpack. Here is a quickstart : https://basarat.gitbooks.io/typescript/content/docs/quick/browser.html
Here is a fairly large project that uses this method http://alm.tools/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.