简体   繁体   中英

How can I use a typescript file in multiple projects some using modules (node.js) and some don't?

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

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/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM