-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Troubleshooting
If you get stuck, try raising an issue or contacting @Rich_Harris on Twitter.
You probably already know that 'eval
is evil', at least according to some people. But it's particularly harmful with Rollup, because of how it works – unlike other module bundlers, which wrap each module in a function, Rollup puts all your code in the same scope.
That's more efficient, but it means that the shared scope is 'polluted' whenever you use eval
, whereas with a different bundler, modules that didn't use eval would not be polluted. A minifier can't mangle variable names in polluted code, because it can't guarantee that the code to be evaluated doesn't reference those variable names.
Furthermore, it poses a security risk in that a malicious module could access another module's private variables with eval('SUPER_SEKRIT')
.
Luckily, unless you really do intend for the evaluated code to have access to local variables (in which case you're probably doing something wrong!), you can achieve the same effect in one of two ways:
Simply 'copying' eval
provides you with a function that does exactly the same thing, but which runs in the global scope rather than the local one:
var eval2 = eval;
(function () {
var foo = 42;
eval('console.log("with eval:",foo)'); // logs 'with eval: 42'
eval2('console.log("with eval2:",foo)'); // throws ReferenceError
})();
Using the Function constructor generates a function from the supplied string. Again, it runs in the global scope. If you need to call the function repeatedly, this is much, much faster than using eval
.