Introduction
One of the best practices while designing efficient lightning web component is to use utility javascript files to define the helper methods. This keeps the primary JavaScript file in your LWC module cleaner to read and debug. Most importantly to achieve reusability. In this blog, I would discuss & demonstrate the exporting-importing javascript functions.
Export within a module
Let's discuss this an example. Say I am developing a LWC module(homeComponent) in LWC to calculate certain maths equations. I need some functions to calculate difference between 2 numbers, products of 2 numbers etc. I received a JavaScript file(utility.js) from my fellow developer with these 2 methods defined. I just need to call those 2 methods in from my LWC.
Step 1 - would be to include the utility.js into my module homeComponent.
Step 2 should be exporting the functions in utility.js in order for homeComponent.js to consume it.
Step 3 would be to import the functions in homeComponent.js and use them.
When the connectedCallback is called, following would be printed in the browser console.
So, we have successfully imported two functions from our utility.js to our homeComponent.js file and used them.
This approach is called named export where we are specifying multiple functions to be exported.
Let me go one step further introduce another method in the utilty.js and make that as our exported method and keep the calculateDifference and calculateProduct methods as private methods. This way this I will only have to export one method and keep everything else in the utility.js as private.
Now importing the calculate function in similar way as previous one.
The browser log would look something like this now.