Skip to content

Using shared classes for single output client and common.js based node.js code #5094

Closed
@andrewvarga

Description

@andrewvarga

I have a general question about project structures / modules.
It's a project with 3 types of code:

  • client: classes used for the client web-app, built into a single js file (with --out).
  • server: code running on node
  • shared: classes used by both client and server, typically model classes with functions like validation, etc

My aim is this:

  • use 1 file per 1 class at the source level
  • deploy the client app into a single output file (for performance reasons: better start up time), the server can be deployed as many files (or if possible and makes sense from a perf. point of view it can be a single file too). These can be 2 separate compilations, the client with --out and the server with commonjs.
  • reuse the shared model classes (without duplication) in the client and the server
  • be able to use circular dependencies (although shared code will not depend on client/node code, only the other way around, circular dependencies can only occur in within the client code)

I can't seem to achieve these goals. The problem is this:

  • if I structure the shared code so that I only use the ///<reference.../> tags (like I do in the client) that won't be usable when compiling the server with common.js
  • if I use common.js style requires in the shared code then that won't work for the client's single file --out compilation

These are the options I think I have:

  • switch to using require js (amd) in the client as opposed to references and the single file output, and maybe use some post compile script to concatenate the modules to a single file. However circular dependencies may occur sometimes and that's a big issue I have with require.js
  • switch to using es6 style module syntax and use it on the client and in node with some polyfills/loaders until natively supported
  • switch to using commonjs style modules and load them with browserify on the client
  • do a pre-compilation step and transform the shared code to be eligible once for the client side single output compilation and once for the node.js side common.js compilation. However this can have many caveats and sounds like a hack.

What I'm really looking for is a way for each TypeScript class/file to be able to "say" what is the class it exports, but not specify how it will be consumed, ie. via commonjs or as a single file output. Probably that's not possible though in a simple way?

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions