In LWC you often need to load static resource. In order to load the static resource in LWC you first need to import the static resource into LWC js file.
You can import static resources from the @salesforce/resourceUrl scoped module. Static resources can be archives (such as .zip and .jar files), images, stylesheets, JavaScript, and other files.
The syntax for importing static resource in LWC is below:
import localNameOfResource from “@salesforce/resourceUrl/resourceReference”;
localNameOfResource —A name that you can give to the static resource in LWC js file.
resourceReference—The name of the static resource.
In order to refer the static resource(that has been imported) in the html, assign the localNameOfResource (from above syntax) variable to the local variable and you can refer the local variable in the html and static resource can be accessed inside HTML.
For an example, If you have a image inside the static resource and you wanted to refer the image from the static resource in the LWC, We can do that in the below way.
// miscStaticResource.js
import { LightningElement } from "lwc";
import TRAILHEAD_LOGO from "@salesforce/resourceUrl/trailhead_logo";
import TRAILHEAD_CHARACTERS from "@salesforce/resourceUrl/trailhead_characters";
export default class MiscStaticResource extends LightningElement {
// Expose the static resource URL for use in the template
trailheadLogoUrl = TRAILHEAD_LOGO;
// Expose URL of assets included inside an archive file
einsteinUrl = TRAILHEAD_CHARACTERS + "/images/einstein.png";
}
<!-- miscStaticResource.html -->
<template>
<lightning-card title="MiscStaticResource" icon-name="custom:custom19">
<div class="slds-m-around_medium">
<img src={trailheadLogoUrl} />
<img src={einsteinUrl} />
</div>
</lightning-card>
</template>
I hope this article helps to understand how we can load and refer the static resource files in LWC.
nice content