Hi Developers,
Welcome again and in this tutorial we will see how we can share the code between Lightning Web Components.
To share code between components, create an ES6 module and export the variables or functions that you want to share.
An ES6 module is a JavaScript file that explicitly exports variables or functions that other modules can use. Modules make it easier to structure your code without polluting the global scope.
There are two ways to export functionality from an ES6 module.
A module can export a single default function or variable.
// utilJs.js
export default shpwToast (variant='info', mode='dismissable', title, message) {
const event = new ShowToastEvent({
title: title,
message: message,
mode : mode,
variant : variant
});
return event;
}
To import the method from the utility js file use the syntax like below
// consumerComponent.js
import { shpwToast } from 'c/utilJs';
Refer below video to see the complete code in action
If you have any queries or any other questions you can reach me out @cloudyamit or email me sfdcpanther@gmail.com #SFDCPanther
Reference & Sources
- https://developer.salesforce.com/docs/component-library/documentation/lwc/create_javascript_share_code
- https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.create_components_javascript
- https://hacks.mozilla.org/2015/08/es6-in-depth-modules/
- https://trailhead.salesforce.com/en/content/learn/modules/modern-javascript-development?trail_id=learn-to-work-with-javascript
How can we define the events method in util.js and pass event parameters, like onclick(event)?
1. You have to create a method in your shared JS which will accept parameter and do perform the logic
2. Export that method
3. Import in your main JS Class
4. Use that
Here is the sample method which makes a server (apex) call using utility method and then again calls the success/error methods
const _servercall = (_serveraction, _params, _onsuccess, _onerror) => {
if (!_params) {
_params = {};
}
_serveraction(_params)
.then(_result => {
if (_result && _onsuccess) {
_onsuccess(_result);
}
})
.catch(_error => {
if (_error && _onerror) {
_onerror(_error);
}
});
};