Share JavaScript Code Between Lightning Web Components

Code reuse is important for writing the reusing as much as possible from existing code Especially if it’s good, tested, maintainable, extensible, and documented code. To share code between components, create an ES6 module and use the standard export statement to export the functionality that your module exposes. Your module can use the standard import statement to use other shared modules.

Create Shared Code

To share code between components, create an ES6 module and use the standard export statement to export the functionality that your module exposes. Your module can use the standard import statement to use other shared modules.

 

Use Shared Code

To use the shared code in a JavaScript file, use the standard import statement. For example:

This line imports the utils module in the c namespace.

Note: You can’t load JavaScript code from a static resource currently. For example, if you’re developing an Aura component, you
can reference JavaScript in a static resource using the <ltng:require> tag. This approach doesn’t work for Lightning web
components.

Example

Let’s create an ES6 module and see how it’s used in a Lightning web component. Create a folder for the utils module in the LWC folder in the lightning web component project directory

The folder looks like below.

 

Create a utils.js file in the utils folder. This file is an ES6 module  that is export the isFunction

The utils module exports an isFunction() function that returns whether the provided parameter is a function.

Create a utils.js-meta.xml configuration file for the utils module.

 

 

Use Shared Code 

Now you need to import the above create ES6 module utils .create a lightning web component using this command

 

Use this libcaller.html code.

Use this libcaller.js code

The c-libcaller component imports the utils module and calls the isFunction function exported by the module. The argument passed into isFunction is a function so the result is set to true. The below code shows how to import the utils code

The above below code shows how to call the imported function

 

Use this libcaller.js-meta.xml code

 

 

Push the changes to scratch org and add to layout for testing. When you click the Check Type button it will call then imported isFucntion module and set the value to the result property.