2

With node, I transpile a typescript tsx file int javascript. Then I need to call a function that is described in that javascript code. ES6 modules are used.

I use

writeFileSync('./temp/page1.js', js) // js is the module source code
import page from '../temp/page1.js'

page is here the default export which is a function that I want to call.

That works fine but I wonder if there is a better way to call the function inside the module source code? A way that avoids saving the source code into a temporary file.

eval would not be a security concern, but I think it would not give me the default export, modules are not considered in this old function.

Maybe something node related?

I found https://www.npmjs.com/package/node-eval which would avoid the file saving, although it still requires a filename, which causes some brittleness in my code.

node:module node:vm

are maybe promising, looking at https://github.com/node-eval/node-eval/blob/master/index.js but I have not yet figured out if and how.

Similar, but more related to require: Load node.js module from string in memory

https://github.com/floatdrop/require-from-string did not work either

all the variants with node:vm like

import vm from 'node:vm'
let context = vm.createContext({}, {name:"temp1.mjs"})
vm.runInContext(js, context, {filename: "temp2.mjs"})

result in "Cannot use import statement outside a module"

4
  • What context are you running this in? Web page? Commented Jul 20, 2021 at 23:20
  • in node. In the end this would be a bundler plugin, say a snowpack plugin. Commented Jul 20, 2021 at 23:22
  • 1
    rtm vm: nodejs.org/api/vm.html - depends on your usage, you are probably looking for vm.runInNewContext, it seems you essentially want to execute what's in the js var in a safe way, which you can do with vm module, either in context, new content or this context. Commented Jul 20, 2021 at 23:55
  • yes, there i might find a way, will digg it. thx Commented Jul 21, 2021 at 0:04

1 Answer 1

1

The best way would be nodes vm.Module class

https://nodejs.org/api/vm.html#vm_module_evaluate_options

but that is in draft stage and behind feature flags.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.