我创建了一个foo.ts
像这样:
class Foo{
public echo(){
console.log("foo");
}
}
并输出如下所示的javascript代码:
var Foo = (function () {
function Foo() {
}
Foo.prototype.echo = function () {
console.log("foo");
};
return Foo;
})();
我想在nodejs REPL中调用
echo
函数,但最终会出现如下错误:$ node
> require('./foo.js');
{}
> f = new Foo
ReferenceError: Foo is not defined
at repl:1:10
at REPLServer.self.eval (repl.js:110:21)
at Interface.<anonymous> (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)
at Interface._onLine (readline.js:202:10)
at Interface._line (readline.js:531:8)
at Interface._ttyWrite (readline.js:760:14)
at ReadStream.onkeypress (readline.js:99:10)
at ReadStream.EventEmitter.emit (events.js:98:17)
at emitKey (readline.js:1095:12)
如何实例化该类并调用
echo
函数? 最佳答案
Node.js没有像浏览器window
对象那样的全局泄漏。
要在node.js中使用TypeScript代码,您需要使用commonjs并导出类即
class Foo{
public echo(){
console.log("foo");
}
}
export = Foo;
然后在REPL中:
$ node
> var Foo = require('./foo.js');
{}
> f = new Foo();
要了解有关AMD/CommonJS的更多信息:https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1
关于javascript - 如何在Nodejs REPL中使用Typescript类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24217912/