Share JavaScript Code

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.

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.

// mortage.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 mortage.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';

Example

The complete sample code is in the MiscSharedJavaScript recipe in the Lightning Web Components recipes app.

Tip

Earn a Trailhead badge and learn more about ES6 modules. Modern JavaScript Development