Sub topic 14
Choosing which files a component needs
This chapter assumes you know what each file in a bundle does. You should also know the naming rule: the folder name and every file's base name match. The task now is deciding which files a new component needs and which it can leave out. Extra files add maintenance cost, and missing ones cause deployment errors or components that can't be placed.
Start from the component's role
The right set of files depends on what the component does. Ask three questions:
- Does it render anything?
- Where will it be used, and does anyone need to place it from a point-and-click tool?
- Does it contain logic worth testing on its own?
The answers map to the files below.
The minimum: JavaScript and configuration
Every bundle that you deploy needs the configuration file. Salesforce uses it to read the API version and to decide whether the component is exposed. A component also needs a JavaScript file, because the class is the component.
The smallest useful UI component has three files:
force-app/main/default/lwc/statusBadge/
├── statusBadge.html
├── statusBadge.js
└── statusBadge.js-meta.xmlThe configuration file for a component that is only used inside other components can be very short:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>With isExposed set to false, the component is still usable from the markup of other components, for example <c-status-badge>. It just doesn't appear in App Builder or other tools.
The HTML file: needed only for UI
Add an HTML file when the component renders markup. Skip it in two cases:
- Service modules. A bundle that only exports functions or constants, such as
c/dateUtils, has no UI. It needs only the JavaScript file and the configuration file. - Headless actions. A headless quick action runs code without showing a panel. Its class exposes an
@api invoke()method and has no template.
If a component extends LightningElement and renders UI, it needs a template with a single root <template> element. If you plan to switch between several layouts, you can have more than one HTML file. See the section on multiple templates below.
The CSS file: add it when you have rules to scope
Styles in a component's CSS file apply only to that component's template. Add the file when you have rules that belong to this component alone. Leave it out when the component only wraps base components such as lightning-card and doesn't need custom rules. An empty .css file adds nothing.
Two situations push you toward a CSS file:
- You need a class or element rule that no base component or utility class provides.
- You want to use styling hooks or custom properties to adjust base components in one place.
If several components need the same rules, don't copy the CSS file. Create a CSS-only module and import it, as described below.
Exposure, targets, and configurable properties
Expose a component (isExposed set to true) only when someone has to select it in a tool. Then list the places where it can go with <targets>. Pick the narrowest set that fits the use. A component listed under lightning__RecordPage appears only for record pages, so don't add lightning__AppPage or lightning__HomePage out of habit.
Add a <targetConfigs> block only when an admin should be able to change a value without editing code. Each <property> must match an @api property in the class by name. Add default values so the component works before an admin touches the settings.
| Situation | `isExposed` | Targets | `targetConfigs` |
|---|---|---|---|
| Child component used only in other components' markup | `false` | none | none |
| Service module imported by other components | `false` | none | none |
| Component placed on app pages by admins | `true` | `lightning__AppPage` | usually yes |
| Record page component | `true` | `lightning__RecordPage` | optional |
A property name in targetConfigs that doesn't match an @api property is a common source of errors. Check the spelling and the case when a property doesn't show up in the property panel.
The SVG icon: optional and cosmetic
The SVG icon is a single file named after the bundle, such as statusBadge.svg. It replaces the default icon that App Builder shows next to the component name. It matters only for exposed components. If the component is not exposed, nobody sees the icon, so skip it. If you do add one, keep it as a plain vector with a size that works at small dimensions.
Helper modules: split code, not responsibilities
A bundle can contain extra JavaScript files next to the main class. Use them when the class grows large and part of it has no connection to the component state, such as formatting or validation functions. Import the helper by relative path:
import { LightningElement, api } from 'lwc';
import { formatStatus } from './statusFormatter';
export default class StatusBadge extends LightningElement {
@api status = 'new';
get label() {
return formatStatus(this.status);
}
}// statusFormatter.js
export function formatStatus(value) {
return value ? value.charAt(0).toUpperCase() + value.slice(1) : '';
}Helper files are private to the bundle. Other components can't import them by name, because only the main module is addressed as c/statusBadge. If two components need the same function, move it into its own service module bundle with its own folder, JavaScript file, and configuration file.
Multiple templates: only for truly different layouts
Add a second HTML file only when the component shows structurally different markup depending on state, as in the LoginPanel example from the earlier chapter on render(). If the difference is one element, use lwc:if in a single template instead. Several templates make the bundle harder to read, because the reader has to check which one render() returns. They also split styling: each template uses the same CSS file unless you name template-specific stylesheets.
Shared CSS modules: when rules repeat
Create a CSS-only module when two or more components need identical rules. The bundle holds the stylesheet and nothing else needed for rendering, and other components load it with @import 'c/sharedStyles'; in their own CSS file. Don't create one for rules used by a single component, because it adds a folder and an import for no gain. Check how your project deploys a bundle without a JavaScript file before you rely on this pattern.
Tests: add them where logic can break
A __tests__ folder holds Jest tests for the bundle, named like statusBadge.test.js. Files in this folder are not deployed to the org, so they cost nothing at runtime. Write tests when the component:
- Computes values from public properties, such as the
labelgetter above. - Changes its markup based on state.
- Dispatches events or calls Apex.
A thin wrapper around a single base component with no logic rarely needs a test. A service module with functions that other components depend on almost always does, because a break there spreads.
Here is a small test for the helper's effect on the component:
import { createElement } from 'lwc';
import StatusBadge from 'c/statusBadge';
describe('c-status-badge', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('capitalizes the status', () => {
const element = createElement('c-status-badge', { is: StatusBadge });
element.status = 'open';
document.body.appendChild(element);
return Promise.resolve().then(() => {
const text = element.shadowRoot.textContent;
expect(text).toContain('Open');
});
});
});This test assumes statusBadge.html renders {label}.
Common mistakes
- Mismatched base names.
statusbadge.htmlnext tostatusBadge.jsbreaks the link between them. Keep the exact case. - Exposing everything. Child components with
isExposedset totrueclutter App Builder and create targets you then have to support. - Unused
targets. Each target is a promise that the component works there. Remove targets you haven't tried. - A CSS file for one rule. Check first whether a utility class or styling hook already does the job.
- Copy-pasted helpers. The same function in two bundles will drift. Move it into a service module.
Exercise
You are building a component that formats currency amounts. Other components call it as c/currencyUtils. It renders nothing and admins never place it. Which files does the bundle need, and what should isExposed be?
Show answer
It needs currencyUtils.js (exporting the functions) and currencyUtils.js-meta.xml. It needs no HTML, CSS, or SVG file because nothing renders and nobody selects it in a tool. Set isExposed to false. Add a __tests__/currencyUtils.test.js file, because other components depend on its logic.
Exercise
A component's class has @api recordLimit, and an admin should set it on a record page. The property panel doesn't show it. Name two things in the bundle to check.
Show answer
Check that isExposed is true and that lightning__RecordPage is listed in <targets>. Then check that a <property name="recordLimit" ...> entry sits inside a <targetConfig> whose targets attribute includes lightning__RecordPage, and that the name matches the @api property exactly, including case.