lukehaas/RunJS

Global variable support

Opened this issue · 4 comments

Is it possible to get Global variable support, preferably it could be a preset we change.

use cases:

  1. I want to add import {expect, describe, it} from '@jest/globals'; to a jest preset so I can run/write tests
  2. I want to add custom/npm installed mocks such as mocks for window

Thanks, @jonniedarko.
I can't quite see the benefit of having globals like this when you can just import whatever you need. Also, when you import what you need, you have control over versions etc. If this was built in, you'd be stuck with the built-in version.

Regarding jest testing, jest is built to be run from a CLI, I don't think it can actually be run programmatically. But I could be wrong.

I have the same feature request but for a different reason.

I use RunJS often as a Node.js Repl replacement. By default the Node Repl is configured to add some builtin modules to the current global context. It would be nice if I could configure RunJS to do the same.

@lukekarrys I thought the Node repl builtins were just the same as the Node builtins?
You're saying you can configure the Node repl to include 3rd party libraries?

You're saying you can configure the Node repl to include 3rd party libraries?

No (sorry for the confusing language). The Node REPLServer (require('node:repl').REPLServer) can be configured that way. The internal Node repl uses that REPLServer but can't be configured to change the builtins directly.

You can set process.env.NODE_REPL_EXTERNAL_MODULE but then you need to provide the entire repl.

Snippets to the rescue

I did come up with a snippet that I made easy to trigger at the top of a RunJS repl to quickly get all the builtins I need which unblocks this use case for me.

require('module').builtinModules
  .filter((b) => !(b.startsWith('_') || b.includes('/') || ['module', 'trace_events', 'vm'].includes(b)))
  .forEach((b) => global[b] = require(b))