You have a String
of JavaScript code. How can you execute it? This is a playground for testing various dynamic script execution methods in Node.js and what features they may or may not support.
vm
Node.js documentation- MDN docs for
eval
- Research for
node-retrieve-globals
. import("data:…")
approach from2ality.com
import("blob:…")
approach suggested by David Bushnell (not currently supported in Node.js but works in Deno!)
JavaScript Feature | Module#_compile |
Function() |
vm.Script |
vm.Module |
import("data:…") |
---|---|---|---|---|---|
Assign module.exports (CommonJS-only) |
Yes | No | Yes | No5 | No |
export (ESM-only) |
No | No | No | Yes1 | Yes |
require |
Yes | Yes | Yes | Yes1 | No |
import (ESM-only) |
No4 | No4 | No4 | Yes1 | No |
Dynamic import() |
Yes | Yes | Yes2 | Yes1 | No |
Top level async or await |
Faux3 | Faux3 | Faux3 | Yes1 | Yes |
Can leak to global scope | Yes | Yes | No | No | Yes |
Notes:
- Requires
--experimental-vm-modules
. Use outputs anExperimentalWarning
to the console. - Requires
vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
an experimental Node feature added in v21.7.0, v20.12.0. Any use outputs anExperimentalWarning
to the console. - Requires the code to be wrapped in an
(async () => {})()
IIFE wrapper. - Can use
esm-import-transformer
to transform staticimport
to dynamicimport()
orrequire
: https://github.com/zachleat/esm-import-transformer - Probably shimmable but I think that would cause more confusion than it’s worth.
- A lot of the pain here is due to unstable
vm.Module
. If you already have access to a transpiler (e.g.esbuild
), use that to output CommonJS code and run it throughModule#_compile
to bypass current limitations with dynamic ESM in Node.js.- Vite writes a temporary file to the filesystem to workaround this issue.
- Some more discussion on Mastodon.