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

2

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?

Siamese answered 5/9, 2018 at 21:19 Comment(0)
S
10

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

$ ts-node
> import * as abc from './my-file'
> abc.myFunction()
> "works!"
Siamese answered 5/9, 2018 at 21:24 Comment(4)
Nice! Thanks very much.Chamomile
Bear in mind that as of now, this won't work if you have noUnusedLocals set in your compiler options. See 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.Primer
I get: Cannot use import statement inside the Node.js REPL, alternatively use dynamic import. See: #73073719Flap
Nope, this doesn't work anymore.Whorton
O
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

Overside answered 30/4, 2021 at 8:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.