How to provide source map in Nodejs VM

376 views Asked by At

I am evaluating javascript bundled source code in nodejs using the below code

const javascriptCode = "..."
const javascriptSourceMap = "..."
const wrapper = NativeModule.wrap(javascriptCode);
const script = new vm.Script(wrapper, {
    displayErrors: true
});
script.runInNewContext();

When there is an error in the source code I get errors like this because no source maps are provided

ReferenceError: a is not defined
    at VueComponent.testSomething (evalmachine.<anonymous>:43112:7)
    at VueComponent.testSomethingAgain (evalmachine.<anonymous>:43109:12

How to provide source maps to VM so that I can get proper filenames instead of evalmachine.<anonymous>?

Thanks in advance

2

There are 2 answers

0
Jenny On

try

require('vm').runInThisContext('console.log(2);\ninvalidJsHere ?= 1;', 'foobar.js');

then you get

foobar.js:2
invalidJsHere ?= 1;
               ^

SyntaxError: Unexpected token =
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
0
Reuben Thomas On

I believe that vm.Script does not support source maps in stack traces as of Node 21.7.1. See https://github.com/nodejs/node/issues/52102