TypeStrong / ts-node

TypeScript execution and REPL for node.js
https://typestrong.org/ts-node
MIT License
12.75k stars 529 forks source link

Support clearing the local context with .clear when starting programmatically #2095

Open lilactown opened 7 months ago

lilactown commented 7 months ago

Desired Behavior

When starting a REPL using node, .clear is an alias for .break

$ node
> .help
.break    Sometimes you get stuck, this gets you out
.clear    Alias for .break
.editor   Enter editor mode
.exit     Exit the REPL
.help     Print this help message
.load     Load JS from a file into the REPL session
.save     Save all evaluated commands in this REPL session to a file

Press Ctrl+C to abort current expression, Ctrl+D to exit the REPL

However, if you start the REPL programmatically, .clear will also clear the local context, allowing you to redefine variables. This is very useful when reloading files or in general doing REPL-driven development.

$ node -e "require('repl').start()"
> .help
.break    Sometimes you get stuck, this gets you out
.clear    Break, and also clear the local context
.editor   Enter editor mode
.exit     Exit the REPL
.help     Print this help message
.load     Load JS from a file into the REPL session
.save     Save all evaluated commands in this REPL session to a file

Press Ctrl+C to abort current expression, Ctrl+D to exit the REPL
> let a = 1
undefined
> let a = 2
Uncaught SyntaxError: Identifier 'a' has already been declared
> .clear
Clearing context...
> let a = 2
undefined

It would be great if ts-node could support this same behavior. Currently, attempting to start the ts-node REPL programmatically gives the same behavior as if started from the CLI, i.e. .clear does not clear the local context.

$ cat repl
#!/usr/bin/env node

let tsNode = require('ts-node');
let repl = tsNode.createRepl();
let service = tsNode.create({...repl.evalAwarePartialHost});
repl.setService(service);
repl.start();
$ ./repl
> let a = 1
undefined
> .clear
> let a = 1
<repl>.ts:4:5 - error TS2451: Cannot redeclare block-scoped variable 'a'.

4 let a = 1;
      ~
<repl>.ts:5:5 - error TS2451: Cannot redeclare block-scoped variable 'a'.

5 let a = 1
      ~

Is this request related to a problem?

Somewhat related to https://github.com/TypeStrong/ts-node/issues/472

Alternatives you've considered

None really. The linked issue says that ts-node wants to keep parity with node, and not add any other magic invalidations. The behavior suggested here is consistent with node.

Additional context

N/A