Member-only story

Code splitting and dynamic function invocation Node js

Asad Iqbal
Oct 30, 2020

--

Code splitting is one of the best feature of web pack, it allows you to split your code in various bundles which can be called on demand in app life cycle. This has a significant impact on application load times.

you can simply write

var required_module = ‘any module’

// you can provide the value on runtime if it is provided as parameter

import(required_module).then((module)=>{

// module object returned

})

I recently came across a need to call any function from node modules based on parameters provided. The function name was passed as string.

If you console.log(module) you will see in your console something like

[Module] {
default: { Type2: [Function: Type2], default: [Function: Type] }

You can see that the module contains default object which contains all exports from module, within the default object there will be named keys containing functions, including one default key which is the default export function.

In order to invoke your funtion you will have to write

var returnVal = module.default[“function_name”](params);

The required function will be executed, saving you a lot of additional lines of code and conditional nesting.

Before parameterizing your module loads you can always check the node_modules folder which contains all the installed modules, check the folder structure of installed module to reference the module name properly if the code doesn't find your module.

--

--

Asad Iqbal
Asad Iqbal

No responses yet