4

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?

Josh Wulf
  • 4,727
  • 2
  • 20
  • 34

1 Answers1

5

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.

Fenton
  • 241,084
  • 71
  • 387
  • 401
  • When I compile my typescript file, I get the same output using the commonjs and amd flag. Should the output be different? Here is my typescript file: `module Foo { export class Bar { private messageType:string; constructor(messageType:string,content:Object){ this.messageType=messageType; } } }` – John Feb 09 '16 at 08:28
  • 1
    I recommend avoiding the `module` keyword when using external modules - the file is your module. Also, the only difference in output is how modules are imported, which is why you see no difference if you have no imports. If you use the module kind `umd` it will work in browsers and on node, so the output can be more easily shared around. – Fenton Feb 09 '16 at 09:48