Accessing Static Resources In LWC!
In Salesforce, you can enhance the functionality and design of your org by importing static resources from the @salesforce/resourceUrl scoped module.
Static resources can include various types of files such as archives (e.g., .zip and .jar files), images, stylesheets, JavaScript, and more.
To import a static resource, use the following syntax:
import myResource from "@salesforce/resourceUrl/resourceReference";
import myResource from "@salesforce/resourceUrl/namespace__resourceReference";
In this syntax:
- myResource is a name that you assign to the imported static resource.
- resourceReference is the name of the static resource you want to import.
It's important to note the following considerations for static resource names:
- Static resource names should only contain underscores and alphanumeric characters.
- The name must be unique within your org.
- It cannot start or end with an underscore.
- It cannot contain consecutive underscores.
If the static resource is part of a managed package, include the namespace of the package in the syntax.
Here's an example to help illustrate the concept:
In the following JavaScript code, we import two static resources: the Trailhead logo and an image of a Trailhead character.
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 URLs for use in the template
trailheadLogoUrl = TRAILHEAD_LOGO;
// Expose URLs of assets included inside an archive file
einsteinUrl = TRAILHEAD_CHARACTERS + "/images/einstein.png";
}
In this example, TRAILHEAD_LOGO and TRAILHEAD_CHARACTERS are the resource references for the static resources.
By assigning these references to variables, we can easily access and use the static resource URLs in the template.
If a static resource is an archive file with a nested directory structure, you can create the path to a specific item within the archive by concatenating strings, as shown in the einsteinUrl variable.
To reference a static resource in your template, you can use the {property} syntax, which is the same syntax used to reference any JavaScript property.
This allows you to seamlessly incorporate the static resource into your visual components, enhancing the overall user experience.
Follow Us