Share module between client and server with TypeScript

笑着哭i 提交于 2019-12-10 17:28:46

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/13113995/share-module-between-client-and-server-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!