Sub topic 12
Shared CSS modules
This chapter covers CSS-only modules in a Lightning web component bundle. These are components that hold styles and nothing else, so other components can import them. It assumes you know how a bundle is laid out, how the c namespace maps to module names, and that CSS in a component is scoped to that component's template.
The problem shared CSS solves
Each component's CSS file applies only to that component's own template. This scoping is useful, but it means a rule written in cardA.css has no effect in cardB. If ten components need the same button look, you have two poor options: paste the rule into ten files, or leave the rules out and rely on the Salesforce Lightning Design System (SLDS) alone.
A CSS-only module is the third option. You write the rules once in one bundle and import that bundle into the CSS files that need it.
What a CSS-only module is
A CSS-only module is a component bundle whose folder contains a CSS file named after the folder, and no HTML or JavaScript file. The bundle in this chapter is called sharedStyles.
force-app/main/default/lwc/
└── sharedStyles/
└── sharedStyles.cssThe usual naming rules still apply. The folder name and the file's base name must match. The folder name starts with a lowercase letter and uses camel case, so sharedStyles is valid and shared-styles or SharedStyles is not.
The module is imported by its module name, which is the namespace and the folder name joined by a slash. In a default project the namespace is c, so sharedStyles becomes c/sharedStyles.
.card-body {
padding: 1rem;
}
.card-title {
color: #032d60;
font-weight: bold;
}
.is-muted {
color: #5c5c5c;
}Save this as sharedStyles.css. It is ordinary CSS. Nothing in the file marks it as shared. It is shared because other components import it.
Importing a shared module
A component imports the module with an @import rule at the top of its own CSS file.
@import 'c/sharedStyles';
.card-body {
border-top: 1px solid #c9c9c9;
}The imported rules are treated as if they were written in the importing file. The importing component's template can use card-body, card-title, and is-muted without defining them.
Three points about this behavior:
@importrules must come before any other rule in the file. Put them at the top, as in the example.- The module name uses the same form as a JavaScript import:
namespace/folderName. Do not write a relative path or a file extension. - A rule in the importing file can add to or override an imported rule. Order and normal CSS specificity decide the result, as they do within a single stylesheet.
Scoping still applies
Importing does not make styles global. The imported rules are applied to the importing component's template, so they stay scoped to that component. Two components that both import c/sharedStyles each get their own scoped copy of the rules. A third component that does not import the module is unaffected.
The reason this matters is that a shared module is not a way to restyle other components from the outside. It lets you reuse source text, not reach across component boundaries. A parent that imports c/sharedStyles does not style the child components inside its template, because the child templates are scoped separately.
Using the module from a component
Here is a complete small example. The bundle orderCard imports the shared module and uses its classes in markup.
<template>
<div class="card-body">
<p class="card-title">Order {orderNumber}</p>
<p class="is-muted">Placed by {customer}</p>
</div>
</template>import { LightningElement, api } from 'lwc';
export default class OrderCard extends LightningElement {
@api orderNumber;
@api customer;
}@import 'c/sharedStyles';
.card-body {
border-top: 1px solid #c9c9c9;
}The template uses three classes, but the component's own CSS file defines only one. The other two come from the import.
Importing other kinds of CSS
The @import rule in a component's CSS file works with CSS-only modules in your own namespace and in installed packages, using that package's namespace in place of c. If you need to share values rather than whole rules, consider CSS custom properties. A shared module can set the values, and each component's rules can read them with var(). Custom properties are inherited through the DOM, including across component boundaries, so they suit theming better than shared rule sets do.
Use these two tools for different jobs:
| Need | Better tool |
|---|---|
| Same rules reused in several components | CSS-only module with `@import` |
| One value (a color or spacing) that can be themed | CSS custom property with `var()` |
| Standard Salesforce look | SLDS classes, no custom CSS |
| Restyle a child component from its parent | Styling hooks the child exposes, not a shared module |
Edge cases and common errors
The module does not resolve. An import such as @import 'c/sharedStyles'; fails if the folder is misnamed or the file name does not match the folder. Check that sharedStyles/sharedStyles.css exists and that the case matches exactly. Casing matters on the module name.
Adding HTML or JavaScript to the bundle. If you add a template or class to the folder, it becomes a regular component. It can still be imported into CSS, but it is no longer a CSS-only module, and it will appear as a component that someone could try to place on a page. Keep the shared bundle free of other files if you want a pure style library.
No configuration file needed. A CSS-only module has no js-meta.xml file in the example above. It is not exposed in App Builder, and it has no targets. If your deployment tooling or a team convention requires a metadata file for every bundle, add one, but treat that as a project rule and not a feature of the module.
Import placed after other rules. An @import that comes after a normal rule is ignored by CSS parsers. Always keep imports first.
Expecting global effects. Setting a rule in the shared module does not change components that do not import it. If a rule seems to do nothing, check that the component's CSS file imports the module and that the template uses the class name exactly.
Cascading surprises. Imported rules and local rules sit in the same stylesheet, so a local rule with equal specificity that appears later wins. Place local overrides after the import.
Testing and maintenance
A CSS-only module has nothing to unit test with Jest, because there is no class to create. Jest in LWC does not apply real stylesheet rules to elements in tests. To verify that a component uses the correct classes, assert on the class names in the rendered DOM, as you would for any component.
import { createElement } from 'lwc';
import OrderCard from 'c/orderCard';
describe('c-order-card', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('uses the shared card classes', () => {
const element = createElement('c-order-card', { is: OrderCard });
element.orderNumber = '1001';
element.customer = 'Ada';
document.body.appendChild(element);
return Promise.resolve().then(() => {
const title = element.shadowRoot.querySelector('.card-title');
expect(title.textContent).toBe('Order 1001');
});
});
});When you rename a class in the shared module, search the project for the old name. The import is resolved by module name, but class names in templates are plain strings, so nothing warns you when a template still refers to a class that no longer exists.
How it fits into choosing files
A shared CSS module is the right choice when two or more components repeat the same rules and those rules are likely to change together. For a single component, keep the styles in its own CSS file. Creating a module for one user adds a bundle to maintain and no benefit.
Exercise
You create the folder shared-styles containing shared-styles.css and try @import 'c/shared-styles'; in another component. What is wrong, and what is the corrected import after you fix it?
Show answer
Component folder names must be camel case, starting with a lowercase letter, and cannot contain hyphens. Rename the folder and file to sharedStyles and sharedStyles.css, then import it with @import 'c/sharedStyles';.
Exercise
Component parentPanel imports c/sharedStyles, and its template contains a child component c-order-card. The child's template uses .is-muted, but orderCard.css does not import the module. Does the child get the muted style? Why or why not?
Show answer
No. Imported rules are scoped to the template of the component whose CSS file imports them. orderCard has to import c/sharedStyles itself to use .is-muted.