4

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

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

1 Answer 1

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
}
3
  • 1
    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, 2020 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? Feb 21, 2020 at 17:33
  • @SebastianKessel - while I can't speak for the OP, I'm guessing his static resource example might be a stand-in for a 3rd party library like this one which I cannot find any documentation for outside of the "D3.js" example on the lwc-recipes site
    – bkwdesign
    Mar 18, 2022 at 19:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .