1

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

  • Could you store those functions in a non-UI LWC component instead? Then life gets easier – Sebastian Kessel Feb 21 at 17:22
  • can you give a more detail explanation? thanks – clin Feb 21 at 17:24
  • answered below, hope it helps – Sebastian Kessel Feb 21 at 17:27
3

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
}
| improve this answer | |
  • Thanks for the quick respond much appreciated! but the goal is to see if we are able to call the java script function the way in the snippet. Is this something we able to accomplish in lwc? – clin Feb 21 at 17:32
  • 1
    Why do you need this in a static resource? I never attempted this with a SR so I can't answer that for you. Is it not a possibility to write the functions in a LWC component instead? – Sebastian Kessel Feb 21 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.