How To Add Static Resources In LWC

Today we will see how to add static resources  in LWC.

Static resources can be archives (such as .zip and .jar files), images, style sheets, JavaScript, and other files.

import myResource from '@salesforce/resourceUrl/resourceReference';
import myResource from '@salesforce/resourceUrl/namespace__resourceReference';

  • myResource—It refers to static resource name
  • resourceReference—The name of the static resource.A static resource name can contain only underscores and alphanumeric characters, and 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.
  • namespace—If the static resource is in a managed package, this value is the namespace of the managed package.

Steps:

  1. First Save the image in Static Resource.

add image

 

  1. Create the LWC component staticResourceDemoInLWC

 

<template>
    <div style="font-weight:bold">
    Here is my Car
    </div>
    <img style="max-height: 400px" alt="MyCar" src={myCar}/>
</template>

 

  1. Create the LWC java-script

 

/*
* @description: access static resource in lwc 
* @author: sfdc4u.com
*/
import {LightningElement} from 'lwc';
import MY_CAR from "@salesforce/resourceUrl/ferariCar";

export default class StaticResourceDemoInLWC extends LightningElement {
    myCar = MY_CAR;
}

 

  1. Create the js-meta.xml
<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

 

Now let’s add this Lightning Web Component on the home page.

  • Go to the Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your staticResourceDemoInLWC component and drag it on right-hand side top.
  • Click Save and activate.

Output:

static resource output

 

Reference: Salesforce.com 

Also Read: Access custom labels in LWC

 

 

 

Leave a Comment