4

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?

CodyBugstein
  • 21,984
  • 61
  • 207
  • 363

2 Answers2

10

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

$ ts-node
> import * as abc from './my-file'
> abc.myFunction()
> "works!"
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
  • Nice! Thanks very much. – Vinicius Carvalho Mar 03 '21 at 20:18
  • 5
    Bear in mind that as of now, this won't work if you have `noUnusedLocals` set in your compiler options. See https://github.com/TypeStrong/ts-node/issues/850. A workaround is to run `ts-node -O '{"noUnusedLocals": false}'` (make sure to use double quotes for the option name) to start up the REPL. – Katie Byers Apr 09 '21 at 16:15
  • 1
    I get: _Cannot use import statement inside the Node.js REPL, alternatively use dynamic import._ See: https://stackoverflow.com/questions/73073219/ts-node-cant-use-dynamic-imports-or-import-statements-while-in-repl-or-eval-in – Jørgen Tvedt Jun 14 '23 at 06:29
  • Nope, this doesn't work anymore. – skrat Jul 21 '23 at 15:51
2

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

Sapan Diwakar
  • 10,480
  • 6
  • 33
  • 43