Salesforce Development Tutorial (LWC): How to create Custom Lightning Web Component Utility Modules

Why create Utility Modules for Lightning Web Components?

If you’re asking this question, I have feeling you don’t often utilize utility modules (or utility classes) anywhere… so let me be the first to welcome you to this absolutely magical world of utilities. They will make your life easier, code updates simpler and your code base a lot less terrifying.

Utility modules are useful in LWC’s because they allow you to take code you commonly use (or may commonly use) between components and allow tons of different components to use that same code without re-writing it a bunch.

Here’s a simple example. Say you pull URL parameters in several different lightning web components and in all of those components you have the exact same method that parses the url and returns those parameters. Instead of adding that method to every single component and having to update that method any time your process for parsing URL parameters change, you could just make a javascript utility module to deal with it, import it into your components and just call that single javascript utility module everywhere you needed to parse URL parameters. In the end this greatly reduces your codebase and the difficulty updating your code in the future.

Maybe the above is still confusing, no worries, let’s check out an example that will hopefully clear any confusion up.


How to create a Utility Module

So to give you a little background on what we’re about to do, I would suggest a little light reading on ES6 Javascript Modules. This will give you a bit better understanding on how all this code I’m about to show you works. If you’re not as obsessive of a reader as me, don’t worry though, I’ll explain everything just a bit throughout the rest of this post.

The first thing we need to do is create an LWC and delete the html file that comes with it as well as all the pre-built code in the javascript file. You might be like wutttttttt??????? But no worries, with utility modules you won’t need them. I know it feels weird right now, but just trust ya boi for one sec.

Next let’s take a look at a very simple LWC module with some exports in it. The name of the below LWC is “util_module”. Knowing the below components name will be important in the near future (GitHub where this code is also available).

//DISCLAIMER: There are many different ways available in ES6 JS to export variables, functions and classes
//you can find out more about exports here: https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

//How to export a variable and make it available when importing your module
//in other components
export const OPEN_STATUS = 'Open';

//How to export a method and make it available when importing your module
//in other components
export function showError(error) {
    return 'This is an error ' + error;
}

//How to export a class and make it available when importing your module
//in other components
export class util_class {

    newStatus = 'New';

    showConsoleLog(){
        console.log('This is the console log ::: ');
    }

}

So what is all that junk up there? It’s not all that complicated after you get familiar with it. Basically what you are seeing are a handful of ways to make things accessible in a javascript module. The key thing here is that “export” keyword. Placing the export keyword in front of a variable, function or a class will allow you to import them into other components. Which brings us to the next part of this lesson, “How tf do we use this utility module”. Let’s check that out.


How to Import/Use your LWC Utility Module

Alright my guys (and gals), let’s check out the code to import that adorable little utility class we made up there into one of our normal LWC’s .

import { LightningElement } from 'lwc';

//Importing in our javascript utility module. The import variable names (OPEN_STATUS, //showError, util_class)
//are the names of the exported variable, method and class in our util_module component
import { OPEN_STATUS, showError, util_class} from 'c/util_module';

export default class Demo_component extends LightningElement 
{
    openStatus;
    returnedError;
    newStatus;

    //The connectedCallback method runs on component load
    connectedCallback()
    {
        //assigning our imported OPEN_STATUS value to our local openStatus variable
        this.openStatus = OPEN_STATUS;

        //assigning our imported showError methods return value to our local returnedError 
        //variable 
        this.returnedError = showError('Tacos had an error');

        //assigning our imported class's newStatus variable to our local newStatus variable
        this.newStatus = new util_class().newStatus;

        //Calling our imported class's showConsoleLog method
        new util_class().showConsoleLog();
    }
}

You’re thinking one of two things right now. It’s either, “Whoa my guy, it’s really that easy?” or, “Idk wtf that mess means”. For the group in latter, let me help you get into the former group with a little bit of an explanation.

Near the top of our LWC you’ll notice this line:

import { OPEN_STATUS, showError, util_class} from 'c/util_module';

This statement is importing the this various things we marked with the “export” keyword in the util_module LWC we created above. You will notice that the OPEN_STATUS, showError and util_class all are the exact names of the things with the “export” statement next to them in the util_module LWC.

These OPEN_STATUS, showError and util_class imports now become accessible in your class via those keywords. So for instance when we do this assignment:

this.openStatus = OPEN_STATUS;

We are literally assigning the OPEN_STATUS variable value from our util_module LWC to our local openStatus variable. Pretty cool right? Hopefully this makes things a little clearer… maybe… If I’m lucky anyway.

And that’s really it everyone! If you have any questions feel free to ask. I typically respond pretty quick.


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture

Similar Posts