Use Static Resource In Lightning Web Component

As a Salesforce developer we know how important Static resource are. We can upload and can refer them using CDN also. But it is always suggested to import third party library into salesforce static resource. If you still didn’t started Lightning Web Components ( LWC ) you can do that here. Due to Lightning Web Components content security policy requirement we need to upload our external files in static resource first. So today we will learn how we can use static resource in LWC and we will also check how it is different then lightning.

For demo purpose I have upload a basic zip file which include one CSS file, jQuery and two images.

 Static Resource in Lightning Web Components ( LWC ) and in Lightning

lwcStaticResource.html

<template>
        <img src={customImage}/>

        <div class="lwcClass">I'm in Lightning Web Components ( LWC )</div>
</template>

lwcStaticResource.js

import { LightningElement } from 'lwc';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import customSR from '@salesforce/resourceUrl/customSR';

export default class LwcStaticResource extends LightningElement {
    customImage = customSR + '/LwcDemo.jpg';  

    renderedCallback() {

        Promise.all([
            loadScript(this, customSR + '/jquery.min.js'),
            loadStyle(this, customSR + '/customCss.css'),
        ])
            .then(() => {
                alert('Files loaded.');
            })
            .catch(error => {
                alert(error.body.message);
            });
    }
   
}

In Lightning Web Components ( LWC ) we first need to import loadScript, loadStyle to load the static resource file. There syntax is loadStyle(self, fileUrl): where in self we need to pass this and in URL we need to pass the URL of static resource file. For image we can direct access URL. In case of multiple files we can do this.

Promise.all([
    loadScript(this, resourceName + '/lib1.js'),
    loadScript(this, resourceName + '/lib2.js'),
    loadScript(this, resourceName + '/lib3.js')
]).then(() => { /* callback */ });

If you have directly uploaded your JS, CSS files in static resource without making a zip then you need to refer them using below code

import jquery from '@salesforce/resourceUrl/jquery';
import bootstrap from '@salesforce/resourceUrl/bootstrap';

Promise.all([
        loadScript(this, jquery),
        loadStyle(this, bootstrap),
  ]).then(() => { /* callback */ });

Now to achieve similar result in Lightning we need to do below things.

lightningStaticResource.cmp

<aura:component>
    <ltng:require styles="{!$Resource.customSR +'/customCss.css'}"  
        scripts="{!$Resource.customSR +'/jquery.min.js'}" 
        afterScriptsLoaded="{!c.setup}" />

        <img src="{!$Resource.customSR + '/lightningDemo.jpg'}"/>
        <div class="lightningClass">I'm in Lightning</div>

    <c:lwcStaticResource />
</aura:component>

lightningStaticResource.js

({
    setup : function(component, event, helper) {
        if (typeof jQuery != 'undefined') {
            alert('jquery loaded in lightning.');
        }
    }
})

As we can see in Lightning resource are loaded in component while in LWC we load them in controller and then use it. So in many area LWC is totally different then Lightning.

Do you want to add anything here or have any question, let me know in comments. Happy programming 🙂

Advertisements

9 thoughts on “Use Static Resource In Lightning Web Component

      1. import { LightningElement } from ‘lwc’;

        import {loadStyle} from ‘lightning/platformResourceLoader’;

        import green from ‘@salesforce/resourceUrl/green’;
        import style from ‘@salesforce/resourceUrl/style’;
        import bootstrap from ‘@salesforce/resourceUrl/bootstrap’;

        export default class eventRequest extends LightningElement {

        renderedCallback() {

        Promise.all([
        loadStyle(this, green + ‘/green.css’),
        loadStyle(this,style+’/style.css’),
        loadStyle(this,bootstrap+’/bootstrap.min.css’),
        ])
        .then(() =>
        {

        })

        }

        }

        ****
        I have three files green.css, style.css, and bootstrap.min.css. I have uploaded to Static Resource like green,style, bootstrap. pls find the above code. The styles are not applied.

        1. It looks like you have directly added the files in static resource instead of zip, So you need to change your code
          loadStyle(this, green ),
          loadStyle(this,style),
          loadStyle(this,bootstrap),

  1. $(function () {
    $(“.dis-date”).datepicker();
    $(“.dis-time”).timepicker({
    showPeriod: true,
    showLeadingZero: true
    });

    // enable/disable the time fields based on an all day Meeting
    $(“.allday”).change(function (event) {
    if ($(‘.allday’).is(‘:checked’)) {
    $(“.dis-time”).timepicker(‘disable’);
    $(‘.dis-time’).removeClass(‘dis-required’);
    }
    else {
    $(“.dis-time”).timepicker(‘enable’);
    $(‘.dis-time’).addClass(‘dis-required’);
    }
    });

    How do I render the Date /Time picker Jquery/Bootstrap CSS through script in LWC ?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.