Static Resources in LWC

By in
5087
Static Resources in LWC

In Salesforce, you can import static resources from the scoped module @salesforce/resourceUrl. Static resources in LWCs include images, style sheets, JavaScript, and archives (like.zip and.jar files).

import myWgResource from ‘@salesforce/resourceUrl/resourceWgReference’;

import myWgResource from ‘@salesforce/resourceUrl/namespace__resourceWgReference’;

  • myWgResource—A name that refers to the static resource
  • resourceWgReference—The name of the static resource.

A static resource name in LWC must be distinct inside your organization and may only contain underscores and alphanumeric letters. It must start with a letter, lack spaces, not have an underscore at the end, and not have two underscores in a row.

  • namespace is the namespace of the managed package if the static resource is in a managed package.

 

Static Resource Example

Let’s examine a few examples of code. A Trailhead logo and a picture of a Trailhead character are imported into the JavaScript code.

// miscWgStaticResource.js

import { LightningElement } from ‘lwc’;

import TRAILHEADWG_LOGO from ‘@salesforce/resourceUrl/trailhead_logo’;

import TRAILHEADWG_CHARACTERS from ‘@salesforce/resourceUrl/trailhead_characters’;

 

export default class MiscWgStaticResource extends LightningElement {

 

// Expose the static resource URL for use in the template

trailheadLogoUrl = TRAILHEADWG_LOGO;

// Expose URL of assets included inside an archive file

einsteinUrl = TRAILHEADWG_CHARACTERS + ‘/images/einstein.png’;

}

 

An archive file with nested directories might be a static resource. To create the route to an item in an archive, concatenate a string as shown in the example to build einsteinUrl.

Use the property syntax, which is the same syntax you use to reference any JavaScript property, to refer to a resource in a template.

<!– miscWgStaticResource.html –>

<template>

<lightning-card title=”MiscWgStaticResource” icon-name=”custom:custom19″>

<div class=”slds-m-around_medium”>

<img src={trailheadWgLogoUrl}>

<img src={einsteinUrl}>

</div>

</lightning-card>

</template>

 

Static resources are located in the /force-app/main/default/staticresources directory in a Salesforce DX project. Subdirectories of staticresources cannot be formed.

For every resource, build a.resource-meta metadata file. The resource’s content type is specified in the metadata file.

 

static resource in lwc Javascript
Image Source: SalesforceCodeCrack

 

Conclusion

In this way, we can use Static Resources in a Lightning Web Component.

To learn more about Lightning web components, check out some of my related blogs below!

 

Additional Resources

Cover Photo by Zach Vessels on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *