How to share code between LWC

To share code between LWC 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.

Share code between LWC Example:-

Your module structure looks like this:

mynamespace
    └──myLibrary
        └──myLibrary.js

There are two ways to export functionality from an ES6 module.

A module can export a single default function or variable.

// myFunction.js
export default myFunction () { ··· }

The component that imports the function chooses a name to refer to the default export. It doesn’t have to be the name of the function or JavaScript file, that’s just a convention. The myFunction.js module is in the recipe namespace.

// consumerComponent.js
import myFunction from 'recipe/myFunction';

A module can also export named functions or variables.

// mortgage.js
const getTermOptions = () => {
    return [
        { label: '20 years', value: 20 },
        { label: '25 years', value: 25 },
    ];
};

const calculateMonthlyPayment = (principal, years, rate) => {
    // Logic
};

export { getTermOptions, calculateMonthlyPayment };

The component that imports the function uses the exported names. The mortgage.js module is in the recipe namespace.

import { getTermOptions, calculateMonthlyPayment } from 'recipe/mortgage';

To create a redirect, you can export all resources from another module with a relative file path.

export * from './utils';