2016-08-13 85 views
1

我创建的非常简单的模块用于测试此尝试的可行性。这里是SPServerApp.ts开头:如何使用Typescript创建node.js模块

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.

+0

您还没有实例化类。添加'新'或创建一个新的实例,你需要它。 – Phix

+1

确实有效。谢谢Phix。 –

+1

我认为这个链接会帮助你。 http://stackoverflow.com/questions/23739044/how-do-you-write-a-node-module-using-typescript –

回答

2

问题是你在调用构造函数时忘了'new'关键字。该行应为:

module.exports = new SPServerApp(); 

如果不使用您的构造函数将被视为正常功能,将刚刚返回undefined(因为你没有明确地返回任何东西)。另外'this'不会指向你在构造函数中所期望的。

省略新的在Node中实际上很常见。但是,对于这个工作,你必须明确地防范稀少调用构造函数,像这样:

constructor() { 
    if (! (this instanceof SPServerApp)) { 
     return new SPServerApp(); 
    } 
    this.AllUsersDict = {}; 
    this.AllRoomsDict = {}; 
} 

顺便说一句,在打字稿你也可以使用模块的语法。 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');