简体   繁体   中英

Dynamically call a javascript function, imported from another module, by name

I'm trying to make some "dynamic" API calls while retrieving some API call templates from a DB.

So what I have to work with is the module name, the function name inside the module and some args to pass on.

And I would like to do something like this :

import someModule;

let someModuleName = "someModule";
let someModuleFunctionName = "someModuleFunction"; // someModuleFunction is declared inside someModule


someModuleName.someModuleFunctionName(args);

I tried to use brackets notation and also apply() with no success.

I must say I am a complete beginner in JS and not a professional coder.

Any thoughts ?

Regards,

try

import {someModuleFunction} from './someModule'
// the path is to be changed to match yours

let say we have a modules.js file with one simple add function

const add(a,b)=> a+b

to import and call the function you'll do this :

import {add} from '.modules"
console.log(add(1,4))

Sort it out this way :

First import the module as an object dynamically with the path built from "static" strings (not working with only variables see: https://webpack.js.org/api/module-methods/ ) and my module name :

const APIlibrary = await import(`path_prefix_to_modules${this.someModuleName}.js`);

Then find the proper APICall (function of the module) in the object (not sure it's the best way...):

const arrayOfAPIFunctions = Object.entries(APIlibrary.default);
const indexOfAPIFunction = arrayOfAPIFunctions.findIndex(x => x[0] == this.someAPICallName);
const APIFunction = arrayOfAPIFunctions[indexOfAPIFunction][1];

Finally make the API call:

APIFunction(args...);

You can use eval function, but be carefully for javascript injection vulnerability!

eval('var dynamicFunction = ' + someModuleName + '.' + someModuleFunctionName);
dynamicFunction(args);

if the content of the variables "someModuleName" and "someModuleFunctionName" are not controlled by you or by some that you trust (like client users), they can inject arbitrary js code that will run, and introduce the vulnerability!

Anyway, it's good practice in this case validate the variables contents, to make sure that will have only valid values, for example only allowing alphanumeric chars, underscore and dollar for the module and function name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM