Split a module between client and server using TypeScript

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

This is a modular thing that stops me. I read http://caolanmcmahon.com/posts/writing_for_node_and_the_browser/ and it looks simple, however gets tsc to create something like this possible?

+4
source share
1 answer

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

So your module file will look like this (without a module declaration)

Mymodule.ts

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

And you should use the following compiler commands to get the result ...

For sites or browsers (recommended)

 tsc --module umd MyModule.ts 

For nodejs

 tsc --module commonjs MyModule.ts 

For browser (using require.js)

 tsc --module amd MyModule.ts 

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

+5
source

Source: https://habr.com/ru/post/1442651/


All Articles