lukehaas / RunJS

RunJS is a JavaScript playground for macOS, Windows and Linux. Write code with instant feedback and access to Node.js and browser APIs.
https://runjs.app
2.01k stars 43 forks source link

Global variable support #569

Open jonniedarko opened 12 months ago

jonniedarko commented 12 months ago

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
lukehaas commented 12 months ago

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.

lukekarrys commented 11 months ago

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.

lukehaas commented 11 months ago

@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?

lukekarrys commented 11 months ago

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))