如何使用Typescript创buildnode.js模块
我创build的非常简单的模块来testing这种努力的可行性。 这是SPServerApp.ts
的开始:
class SPServerApp { public AllUsersDict: any; public AllRoomsDict: any; constructor () { this.AllUsersDict = {}; this.AllRoomsDict = {}; } } module.exports = SPServerApp();
然后在我的应用程序中,我有这个要求声明:
var serverapp = require('./SPServerApp');
然后,我尝试访问这样的字典之一:
serverapp.AllUsersDict.hasOwnProperty(nickname)
但是得到错误:
TypeError: Cannot read property 'hasOwnProperty' of undefined
任何人都可以看到我在这里做错了吗?
谢谢,E.
问题是你在调用构造函数时忘了“new”关键字。 该行应为:
module.exports = new SPServerApp();
如果你不使用new,你的构造函数将被视为一个正常的函数,只会返回undefined(因为你没有明确的返回任何东西)。 另外'这'不会指向你在构造函数中的期望。
在Node中省略new实际上是相当普遍的。 但是为了这个工作,你必须在构造函数中明确地防止新的调用,像这样:
constructor () { if (! (this instanceof SPServerApp)) { return new SPServerApp(); } this.AllUsersDict = {}; this.AllRoomsDict = {}; }
顺便说一句,在TypeScript中,你也可以使用模块语法。 TS编译器将把它转换成export / require语句。 使用ES6风格的模块,你的例子看起来像这样:
export class SPServerApp { public AllUsersDict: any; public AllRoomsDict: any; constructor () { this.AllUsersDict = {}; this.AllRoomsDict = {}; } } export var serverapp = new SPServerApp();
在您刚刚导入的其他TS文件中:
import { serverapp } from './SPServerApp'; serverapp.AllUsersDict.hasOwnProperty('something');