0

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

1 Answer 1

0

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

Example

Here is a fairly large project that uses this method http://alm.tools/

Sign up to request clarification or add additional context in comments.

1 Comment

So you think there isn't a way around it? I am not sure if this will be even possible with all client applications that use my shared library :/ because they need to be loaded asynchronous don't they? The server is also just a tiny project. Probably end up rather having two versions of the SharedLibrary in the end :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.