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.