-->

Sharing TypeScript classes between client and serv

2019-05-10 08:59发布

问题:

I have a Node.js project written in TypeScript. In my project, I have a folder named "public" which contains the client side code & HTML and also a file named classes.ts which is supposed to be shared to the server side.

The problem is that I need to add "export" before the classes declaration in order to make them accessible in the server, but then in the browser I get this Error:

Uncaught ReferenceError: exports is not defined

I found these questions: https://github.com/Microsoft/TypeScript/issues/5094, Setup a Typescript project with classes shared between client and server apps?, Share module between client and server with TypeScript, which suggests using commonjs in the server but amd in the client. The problem with this solution is that they have 3 different projects (server, client and shared) whereas I only have one project in which I use commonjs. Another suggestion is:

the other option, which is more convoluted and will require a post build step to massage the code; if you can not use module loaders in your client code, is to isolate all module dependencies in your server code, then in the shared, they are just classes. Build the shared files without --module, and no exports or imports, but all inside a single namespace, say namespace MyApp { ... }; in your client code, you include them directly, and emit using --out. in your server code, you first emit the shared code to a single file, shared.js, and a single .d.ts shared.d.ts, augment these with some code to export them as a module, e.g. append exports = MyApp at the end of your shared.js and shared.d.ts, then import them from your server code.

But I don't want to deal with updating .d.ts files all the time, and I'm also not sure it will work in one project.

Any suggestion how to make a TypeScript class accessible both in browser and server?

Any help will be profoundly appreciated!

回答1:

This is absolutely possible.

I have a project containing both SPA client application that runs in browser and server running in node.js that both share common typescript classes. For all of this I have just one tsconfig.json file (I am still not sure that this is the best approach but for now it works just fine)

Here are parts of my setup:

  • Use modules (previously called external modules). No need for namespaces and d.ts files for your own modules.
  • module = "commonjs" in tsconfig.
  • On client side use System.js as module loader (this will solve your 'Uncaught ReferenceError: exports is not defined'). You can use angular2 5 min quickstart as reference how to setup system.js.

It works like a charm.