Search code examples
javascriptreactjseval

Why does eval() not work for imported functions?


In React, why does eval() only work for functions that are defined within the same file, but not for imported functions?

In my code example, alertY is an imported function and alertX is defined within the same file. When the function name is passed to onClick, both alertX and alertY works.

However, when the function is directly called inside eval as a string and then passed to onClick, only alertX works. alertY caused a ReferenceError as follows:

Uncaught ReferenceError: alertY is not defined
    at eval (eval at onClick (index.js? [sm]:13)

src/index.js

import { alertY } from "./alertY";

function alertX() {
  alert("x");
}

function App() {
  return (
    <div className="App">
      <button onClick={alertX}>alertX</button>
      <button onClick={alertY}>alertY</button>

      <button onClick={() => eval(`alertX()`)}>evalX</button>
      <button onClick={() => eval(`alertY()`)}>evalY</button>
    </div>
  );
}

src/alertY.js

export function alertY() {
  alert("y");
}

Code Sandbox link

Second question: As shown in Mhd's answer, why does import * as alerts from "./alertY" work while import { alertY } from "./alertY" doesn't?

Thank you for your help.


Solution

  • try this:

    import * as alerts from "./alertY";
    
    function alertX() {
      alert("x");
    }
    
    function App() {
      return (
        <div className="App">
          <button onClick={alertX}>alertX</button>
          <button onClick={alerts.alertY}>alertY</button>
    
          <button onClick={() => eval(`alertX()`)}>evalX</button>
          <button onClick={() => eval(`alerts.alertY()`)}>evalY</button>
        </div>
      );
    }