How to share a code between Aura and Lightning Web component

Now you can build Lightning components using two programming models: Lightning Web Components, and the original model, Aura Components.

Most of the projects consist of Aura Components but more and more developers trying to use LWC for new components. Developers faced with the issue to use common functions in Aura and Lightning Web Components.

The solution is pretty simple:

  1. You need to create simple LWC component with export function, like this
// utils.js
export function mySharedFunc(param1, param2) {
    //your logic here
    return true;
}

2. To use this function from Aura component, you need to add LWC component to Aura cmp and assign aura:id

<c:utils aura:id="utils"/>

then in you Aura JS controller you need to find LWC cmponent and call the function

component.find('utils').mySharedFunc('string', 123);

3. To use this function from LWC component, you need to import your component in JS controller

import { mySharedFunc } from "c/utils";

Now you can call the function from any method

myHandler(value) {
    mySharedFunc('string', value)
}

It’s all. Need a personal consultation? Contact our team.