12

How do you access (referencing) CSS static resource file in Lightning Web Component (LwC) html? I have included the css under the "staticresources" folder and its uploaded in the salesforce static resource section.

I am referring this help doc but don't see how to reference css - https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.create_resources

2 Answers 2

10

You will most likely need to utilize loadStyle(self, fileUrl): Promise from lightning/platformResourceLoader. You can find a sample on Use Third-Party JavaScript Libraries

The platformResourceLoader module has two methods, loadScript and loadStyle. Both methods return promises, which can be chained or used in parallel. You control the load sequence of your scripts or styles.

import resourceName from '@salesforce/resourceUrl/resourceName';
import { loadStyle, loadScript } from 'lightning/platformResourceLoader';

loadStyle(this, resourceName + '/yourstyle.css')
4

I ran into a similar issue. The Salesforce docs show how to reference numerous resources except css, lol. There are a few details worth pointing out that the Salesforce doc doesn't explicitly mention:

I'll assume you are writing this in VSCode and have the default file structure (e.g. force-app\main\default etc.). Let's pretend you have your desired css in a file called myStaticStyles.css. Add myStaticStyles.css to your staticresources folder. Then, create a new file called myStaticStyles.resource-meta.xml file.

And here is what the code will look like:

controller.js

import { loadStyle } from 'lightning/platformResourceLoader';
import myStaticStyles from '@salesforce/resourceUrl/myStaticStyles'
/* notice that it's just myStaticStyles, not myStaticStyles.css.
The LWC framework will automatically compile your .css and .resource-meta.xml files
into the necessary css resource. 
*/
export default class Controller extends LightningElement {
    connectedCallback() {
        loadStyle(this, myStaticStyles); 
        //you can add a .then().catch() if you'd like, as loadStyle() returns a promise
    }
}

myStaticStyles.resource-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
    <contentType>text/css</contentType>
</StaticResource>

There are other tags you can add to configure your settings, but this is all you need to get things working. A .resource-meta.xml file is necessary in order to successfully deploy from source to org.

And your myStaticStyles.css will just have normal css.

Make sure you SFDX: Deploy source to org the static resources folder. Sometimes I would only deploy my component code and not realize the static resources were left behind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.