[SalesForce] Static JavaScript resource with LWC

LWC rookie here, How can we call a JavaScript function from LWC?
For example I have the following static resource helloWorld.js and I'll like to use and call the function in the file. How can I accomplish this?

JavaScript file:

    function helloWorld(name) {
        let hello = 'Hi ' + name;
        return hello
    }

LWC controller:

 import { LightningElement, track, api } from "lwc";
 import helloWorld from "@salesforce/resourceUrl/helloWorld";
 import { loadScript } from "lightning/platformResourceLoader";

 export default class testLwc extends LightningElement {

  @track message;

  renderedCallback() {
    Promise.all([loadScript(this, helloWorld)])
      .then(() => {
        this.error = undefined;
        // Call back function if scripts loaded successfully
        console.log('load correctly')
      })
      .catch(error => { 
      });
  }

  handleOnChange() {  
     //how can I do something like this below ?
     this.message = window.helloWorld('test');  
  }

Thank you

Best Answer

I am going to assume that your objective is to create a common set of functions to share among components. If that is the case, you can do it like so.

a) Create an LWC component without a UI (I called mine utils)

b) Add your functions to the utils.js file like a regular JS module (example with two sample functions below)

const logToTable = (proxyObject) => {
    console.table(JSON.parse(JSON.stringify(proxyObject)));
}

const sleep = (milliseconds) => {
    return new Promise(resolve => setTimeout(resolve, milliseconds))
}

export {
    logToTable,
    sleep
}

c) In your regular LWC, you must import the functions you wish to use

import {sleep, logToTable} from 'c/utils';

d) now you can use them as you'd use any function (this snippet goes on your LWC js)

logSomething(something) {
    logToTable(something);
   //do your thing
}
Related Topic