如何使用 Typescript 创建 node.js 模块
How to create node.js module using Typescript
我创建的非常简单的模块,用于测试这项工作的可行性。这是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 你的构造函数将被视为一个普通函数并且只是 return 未定义(因为你没有 return任何明确的内容)。此外 'this' 不会指向您在构造函数中期望的内容。
在 Node 中省略 new 其实很常见。但是为了让它工作,你必须明确地防止 new-less 构造函数中的调用,如下所示:
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');
我创建的非常简单的模块,用于测试这项工作的可行性。这是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 你的构造函数将被视为一个普通函数并且只是 return 未定义(因为你没有 return任何明确的内容)。此外 'this' 不会指向您在构造函数中期望的内容。
在 Node 中省略 new 其实很常见。但是为了让它工作,你必须明确地防止 new-less 构造函数中的调用,如下所示:
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');