Is it possible to import a Typescript into a running instance of ts-node REPL?

Viewed 2001

I would like to test some Typescript code I've code written.

So far, the best way I know to do this is to run ts-node my-file-name.ts.

However I would like to make this more interactive, similar to how Python REPL allows you to import modules and then call then functions from the REPL however you'd like.

For example, a session might look like

$ ts-node
> import my-file-name.ts
> myFunctionFromMyFile("specialParam")
> "you just called a function from my-file-name.ts with param specialParam"

Is this possible with ts-node?

2 Answers

One way I've found to do this is as follows:

$ ts-node
> import * as abc from './my-file'
> abc.myFunction()
> "works!"

If you need something that is auto-imported on each REPL session, you could expose your app in a file and then use repl.start inside that file. For example, create console.ts like this:

import repl from 'repl';
import * as models from './models';

Object.keys(models).forEach((modelName) => {
  global[modelName] = models[modelName];
});

const replServer = repl.start({
  prompt: 'app > ',
});

replServer.context.db = models;

And run the console using

$ node --require ts-node/register/transpile-only --experimental-repl-await console

More details here

Related