Josh Wulf
Josh Wulf

Reputation: 4877

Share module between client and server with TypeScript

I want to write a portable module that can be reused between the node.js server and the browser.

It's the modularization thing that's stopping me atm. I'm reading http://caolanmcmahon.com/posts/writing_for_node_and_the_browser/ and it looks straightforward, however is getting tsc to generate something like that possible?

Upvotes: 4

Views: 1855

Answers (1)

Fenton
Fenton

Reputation: 250932

If you write your TypeScript in the CommonJS / AMD style (i.e. each file is a module) you can ask the compiler to output either CommonJS (for nodejs server) and AMD (for the browser, using requires.js).

So your module file would look like this (with no module declaration)

MyModule.ts

exports class MyClass {
    constructor (private id: number) {
    }

    // ... etc
}

And you would use the following compiler commands to get the output...

For nodejs OR browsers (recommended)

tsc --module umd MyModule.ts

For nodejs

tsc --module commonjs MyModule.ts

For the browser (using requires.js)

tsc --module amd MyModule.ts

The only difference in compiled output is that the server code will use the CommonJS import statements to load modules and the browser code will call requires.

Upvotes: 5

Related Questions