1

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.

aibars
  • 93
  • 1
  • 10
  • `new Function` functions are created in the global scope, so you'll need to make a `moment` global. Or [use a nested function to inject values with local names](https://stackoverflow.com/a/24032179/1048572). – Bergi Aug 03 '20 at 20:30
  • See also [Function constructed with new Function cannot call other functions](https://stackoverflow.com/q/38426601/1048572) – Bergi Aug 03 '20 at 20:31
  • "*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.*" - can you please elaborate on the environment you are running your code in? It sounds like some file-based module system, like node.js commonjs, or even es6 modules with `import`? – Bergi Aug 03 '20 at 20:32
  • 1
    I was able to solve it by passing moment or any library as a new argument of the function like new Function('moment', ); – aibars Aug 04 '20 at 16:41

0 Answers0