问题描述
我想编写一个可移植的模块,该模块可在node.js服务器和浏览器之间重用.
I want to write a portable module that can be reused between the node.js server and the browser.
是模块化的事情阻止了我的atm.我正在阅读 http://caolanmcmahon.com/posts/writing_for_node_and_the_browser/,它看起来很简单,但是是让tsc生成类似的东西吗?
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?
推荐答案
如果您以CommonJS/AMD风格编写TypeScript(即每个文件都是一个模块),则可以要求编译器输出其中一个CommonJS(用于nodejs服务器)和AMD(对于浏览器,使用require.js).
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...
对于nodejs或浏览器(推荐)
tsc --module umd MyModule.ts
对于nodejs
tsc --module commonjs MyModule.ts
对于浏览器(使用require.js)
tsc --module amd MyModule.ts
编译输出中的唯一区别是服务器代码将使用CommonJS import语句加载模块,而浏览器代码将调用require.
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.
这篇关于使用TypeScript在客户端和服务器之间共享模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!