Share Javascript Code in LWC

By in
1572
Share Javascript Code in LWC

In previous posts, we’ve discussed Lightning Web Components and how they relate to Javascript Code. Today, we will discuss sharing Javascript Code in LWCs.

Create an ES6 module in a service component and use standard JavaScript syntax to export the variables or functions you want to share to exchange code between components.

A JavaScript file that explicitly exports variables or functions for usage by other modules is known as an ES6 module. Code organisation is facilitated by modules.

 

Patterns for Code Sharing

LWC offers two patterns for code sharing:

  1. In the same folder as the component importing the code, create JavaScript files that export code. Make use of a relative path to import the code. This file cannot be directly imported by other components. Instead of exchanging code with other components, this strategy permits arranging code within a component.
  2. Make a service component, also known as a library, which is a component folder that has one or more code-exporting JavaScript files. Other components utilise the c/componentName syntax to import the code. Only the main JavaScript file, which shares the same name as the folder, can be used by components to import code. Export the code from the library’s other JavaScript files, then export it again from the main JavaScript file to share code from those files.
Javascript Code LWC
Image Source: Forcetrails

The first pattern is used in this instance. Only myComponent.js has the ability to import code from myFunction.js and utils.js.

lwc

└───myWgComponent

├──myWgComponent.html

├──myWgComponent.js

├──myWgComponent.js-meta.xml

├──myWgFunction.js

└──wgutils.js

 

Utilize relative paths when importing the code.

// myComponent.js

import { getMonthlyAmount, calculateMonth} from ‘./myWgfunction;

import WgCalender from ‘./wgutils;

 

Another illustration is a service component (library). The name of the folder and one JavaScript file must match. The name in this instance is wgUtils.

 

lwc

├──wgUtils

├──wgUtils.js

└──wgUtils.js-meta.xml

└───wgComponent

├──wgComponent.html

├──wgComponent.js

└──wgComponent.js-meta.xml

 

For importing the code into other components, use c/componentName syntax.

// wgComponent.js

import { getOptions, calculatePayment } from ‘c/wgUtils’;

 

Conclusion

In this way, we can utilize best practices to share code between Lightning Web components and for importing and exporting js functions to different components to enable reusability.

 

Additional Resources

Cover https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.js_share_code

Leave a reply

Your email address will not be published. Required fields are marked *