Home > Net >  Run imported function via another function
Run imported function via another function

Time:11-17

Starting point: With this code I trigger func2 via func1. This works fine so far.

window.addEventListener("click", function (event) {
  func1("func2()")
})

function func1(functionAsString) {
  eval(functionAsString)
}

function func2() {
  alert("success!")
}

The problem: As soon as I import func2 from another javascript file. I can't run func2 with this code anymore.... I have tried it with both import variants

import * as myfunc from "./xy" // myfunc[functionAsString]

as well as

import {func2} from "./xy" // eval(functionAsString)

and unfortunately I do not get func2 addressed.

Can someone give me the decisive tip? Gladly without .eval()

CodePudding user response:

I recreated your problem in a local environment and it works fine

I also did that on codesanbox and it didn't work here

The problem is that in the codesandbox environment parcel was used which transpiles the files and changes the names of the functions hence it couldn't find the name

Anyway, this should work fine in either case:

import * as myfunc from "./xy"
myfunc['func2']()
  • Related