Free computer code on screen

Distribute JavaScript Code within a Lightning Web Component for Accessing URL Parameters

In this article, we’ll craft a Lightning Web Component intended for sharing as a JavaScript library among other LWCs.

We’ll create an LWC Component serving as a utility method to retrieve query parameters, demonstrated below:

//Method to read parameter from query string
export function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search); 
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>false</isExposed>  
</LightningComponentBundle>

As seen in the provided code, creating a JavaScript file and a meta file is all that’s required for the LWC to function as a JavaScript library. Observe the function defined using the ‘export’ keyword. It’s possible to have multiple export methods within the same LWC, allowing their utilization as a library in your project.

To employ the above method in any LWC component, use the following syntax:

<template> 
  ... Some UI related code here
</template>
import { LightningElement , track } from 'lwc'; 
//Importing reusable LWC Component as Javascript utility
import {getUrlParameter } from 'c/JSUtility';

export default class DemoWrapperLWC extends LightningElement {
   //Some track variables define 
   //...... 
   //.. Some code
  
    //Similar to init method in Aura
    connectedCallback() { 
      //Note - We are NOT using "this" keyword to access method getUrlParameter
      let param1 = getUrlParameter('param1'); 
      console.log('Found Parameter value for param1'+param1);
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
        <target>lightningCommunity__Page</target>
        <target>lightningCommunity__Default</target>
    </targets>
  
</LightningComponentBundle>