Friday 15 November 2019

How To Use Static Resource In LWC


Use Static Resource In Lightning Web Components

As we know Static Resources allow you to upload content that you can reference in a component such as .zip and .jar files, images, style sheets, JavaScript, and other files Static resource. And it is very important while customizing salesforce.

To access Static Resources in  Lightning web components first we have to import  from "@salesforce/resourceUrl/<yourResourceName >" to component's js

@salesforce: Modules scoped with @salesforce add functionality to Lightning web components at runtime.


 This will Import your static resources :

import resourceName from '@salesforce/resourceUrl/resourceName';





    Static resource in lwc
  1. From Setup, enter Static Resources in the Quick Find box, then select Static Resources, and then click New.
  2. Enter YourResourceName for the Name.
  3. Click Choose File, and then choose the YourResource file
  4. Click Save.



Let’s look at some sample code:



StaticResourceDemo.js
import { LightningElement } from 'lwc';
import BearLogoURL from '@salesforce/resourceUrl/Bear';
export default class StaticResourceDemo extends LightningElement {
    salesforceBear   =  BearLogoURL;
}
StaticResourceDemo.html
<template>
    <div class="app slds-p-around_x-large">
        <h1 class="slds-text-heading_large">Lightning Web Component</h1>
            <lightning-layout>
                <lightning-layout-item >
                    <lightning-card title="Static Resource..." icon-name="custom:custom9" >
                     <img src={salesforceBear} alt="salesforce Bear Image" />
                </lightning-card>
            </lightning-layout-item>
        </lightning-layout>
    </div>
</template>

Consideration while creating  Static Resources

  • A static resource name can contain only underscores and alphanumeric characters.
  • Must be unique in your org.
  • It must begin with a letter, not include spaces, not end with an underscore, and not contain two consecutive underscores.



3 comments:

  1. Hi, Nishad Kallingal,
    I have same code like that but not able to fetch star getting error. Invalid reference fivestar of type resourceUrl in file fiveStarRating.js

    ReplyDelete