In an API response that I'm integrating with, I receive JS code inside a JSON that I need to execute at run-time.
For that, I normally use the new Function()
statement. While for most cases this works just fine, there are some other cases that contain references to external libraries such as moment or lodash.
Here's an example of such JS string:
{
...
"calculateValue": "value = moment().diff(moment(row.DateOfBirth), 'years');"
...
}
So I create a function by doing new Function('row', 'value = moment().diff(moment(row.DateOfBirth), 'years');')
and then execute it.
However, the error I'm getting is
[ReferenceError: moment is not defined]
Logically, I tried adding a reference to moment in the file where the function is being executed and also tried concatenating the import statement to the string without any luck.
Is there a way of importing external libraries using the "new Function" syntax or using "eval"?
Please bear in mind that I receive these JS strings dynamically by requesting data from a server an cannot actually write those.