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"

citykid
  • 9,916
  • 10
  • 55
  • 91
  • What context are you running this in? Web page? – Brad Jul 20 '21 at 23:20
  • in node. In the end this would be a bundler plugin, say a snowpack plugin. – citykid Jul 20 '21 at 23:22
  • 1
    rtm vm: https://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. – Lawrence Cherone Jul 20 '21 at 23:55
  • yes, there i might find a way, will digg it. thx – citykid Jul 21 '21 at 00:04

1 Answers1

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.

citykid
  • 9,916
  • 10
  • 55
  • 91