如何在Nodejs REPL中使用Typescript类?

时间:2014-06-14 08:05:42

标签: javascript node.js typescript

我创建了一个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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

现代更新:多亏了esm,您可以轻松使用ES模块:

export class Foo{
    public echo(){
        console.log("foo");
    }
}

在REPL中:

$ node -r esm
> import { Foo } from './foo.js';
{}
> f = new Foo();