Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Typescript class in Nodejs REPL?

I created a foo.ts like this:

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

And it outputs javascript code like this:

var Foo = (function () {
    function Foo() {
    }
    Foo.prototype.echo = function () {
        console.log("foo");
    };
    return Foo;
})();

I want to call echo function in nodejs REPL, but it ends up a error like this:

$ 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)

How can I instantiate the class and call the function echo?

like image 254
ironsand Avatar asked Jun 14 '14 08:06

ironsand


2 Answers

Node.js does not have a leaky global like the browser window object.

To use TypeScript code in node.js you need to use commonjs and export the class i.e.

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

export = Foo;

Then in the REPL:

$ node
> var Foo = require('./foo.js');
{}
> f = new Foo();

To learn more about AMD / CommonJS : https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1

like image 80
basarat Avatar answered Oct 14 '22 07:10

basarat


Update for modern times: You can use ES modules easily thanks to esm:

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

In the REPL:

$ node -r esm
> import { Foo } from './foo.js';
{}
> f = new Foo();
like image 1
rm.rf.etc Avatar answered Oct 14 '22 08:10

rm.rf.etc