iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🛠

Launching a customized Node REPL

に公開
2023/01/12

When checking the behavior of JS, it's common to open a terminal and launch an interactive shell using the node command.
Since I sometimes want to use utility functions at that time, I've created an environment where they are pre-loaded.

Creating the REPL Module

title=index.js
import lodash from 'lodash'
import kit from '@elzup/kit'
import repl from 'repl'

// start message
console.log('anozon node repl (^•ω•^)')

const r = repl.start({ prompt: 'node> ' })

Object.defineProperty(r.context, '_', {
  enumerable: true,
  value: lodash,
})

r.context.kit = kit
> node index.js
anozon node repl (^•ω•^)
node> _.range(5)
[ 0, 1, 2, 3, 4 ]

Since assigning lodash directly to r.context._ results in an error, I use Object.defineProperty instead.

Registering as a Local Command

Set up the command name (e.g., anode) in package.json and install it globally.

title=package.json
{
  "description": "personal custom node REPL",
  "main": "index.js",
  "type": "module",
  "bin": {
    "anode": "index.js"
  }
}
> npm i -g .
> anode
anozon node repl (^•ω•^)
node>

You can also modify the startup message and prompt, allowing you to customize it to your preference.

Sample repository:
elzup/anode-repl: personal custom node REPL

GitHubで編集を提案

Discussion