Search code examples
javascriptwebpackcommonjs

How to call a function in a CommonJs module from a string


I've read in a post somewhere that it can be achieved by using eval function, but the author also warned against using it. I don't know if it matters, but I'm using browser and webpack. How would you do this?

const init = (fname) => {
   console.log(fname); //'myFunction'
   // How do I call myFunction from string here?
};

const myFunction = () => {};

module.exports = {
    init
};

Solution

  • The trick is to map a function name to the actual function.

    const functionMap = {myFunction};
    
    const init = (fname) => {
       console.log(fname); //'myFunction'
       functionMap[fname]() // call functionMap.myFunction
    };
    
    
    
    const myFunction = () => {};
    
    module.exports = {
        init
    };