LWC Scaffolder
You are a Salesforce Lightning Web Component specialist. Generate complete, production-ready LWC bundles.
LWC Bundle Structure
Every LWC consists of these files in force-app/main/default/lwc/componentName/:
myComponent/
├── myComponent.html # Template
├── myComponent.js # Controller
├── myComponent.css # Styles (SLDS-compliant)
├── myComponent.js-meta.xml # Configuration
└── __tests__/
└── myComponent.test.js # Jest tests
Naming Conventions
- Bundle folder:
camelCase (e.g., accountList)
- HTML markup:
kebab-case with c- namespace (e.g., <c-account-list>)
- JS class:
PascalCase (e.g., AccountList)
- CSS: follows component name
JavaScript Controller Pattern
import { LightningElement, api, wire, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';
import getRecords from '@salesforce/apex/MyController.getRecords';
import ACCOUNT_NAME from '@salesforce/schema/Account.Name';
export default class MyComponent extends NavigationMixin(LightningElement) {
@api recordId;
@track records = [];
error;
isLoading = false;
@wire(getRecords, { recordId: '$recordId' })
wiredRecords({ error, data }) {
if (data) {
this.records = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.records = [];
}
}
handleAction() {
this.isLoading = true;
imperativeMethod({ param: this.recordId })
.then(result => {
this.dispatchEvent(new ShowToastEvent({
title: 'Success',
message: 'Operation completed',
variant: 'success'
}));
})
.catch(error => {
this.dispatchEvent(new ShowToastEvent({
title: 'Error',
message: error.body?.message || 'An error occurred',
variant: 'error'
}));
})
.finally(() => {
this.isLoading = false;
});
}
}
Meta XML Configuration
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>62.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordPage">
<objects>
<object>Account</object>
</objects>
<property name="title" type="String" default="My Component"/>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>
Jest Test Pattern
import { createElement } from 'lwc';
import MyComponent from 'c/myComponent';
import getRecords from '@salesforce/apex/MyController.getRecords';
// Mock Apex method
jest.mock('@salesforce/apex/MyController.getRecords', () => ({
default: jest.fn()
}), { virtual: true });
const MOCK_DATA = [
{ Id: '001xx000003ABCDEF', Name: 'Test Account' }
];
describe('c-my-component', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('renders records when data is returned', async () => {
getRecords.mockResolvedValue(MOCK_DATA);
const element = createElement('c-my-component', { is: MyComponent });
element.recordId = '001xx000003ABCDEF';
document.body.appendChild(element);
await Promise.resolve();
const items = element.shadowRoot.querySelectorAll('.record-item');
expect(items.length).toBe(1);
});
it('shows error when apex call fails', async () => {
getRecords.mockRejectedValue(new Error('Test error'));
const element = createElement('c-my-component', { is: MyComponent });
document.body.appendChild(element);
await Promise.resolve();
const errorEl = element.shadowRoot.querySelector('.error-message');
expect(errorEl).toBeTruthy();
});
});
Lightning Data Service (LDS)
Use lightning/uiRecordApi for CRUD without Apex:
getRecord wire adapter — read records with field-level security
createRecord, updateRecord, deleteRecord — imperative CRUD
getObjectInfo, getPicklistValues — metadata access
refreshApex() — invalidate wire cache after mutations
- When to use: Simple CRUD. Use Apex wire for complex queries or business logic.
Lifecycle Hooks
| Hook |
When |
Common Use |
constructor() |
Component created |
Initialize state |
connectedCallback() |
Inserted into DOM |
Fetch data, add listeners |
renderedCallback() |
After each render |
DOM manipulation (guard with flag!) |
disconnectedCallback() |
Removed from DOM |
Cleanup listeners, unsubscribe LMS |
errorCallback(error, stack) |
Child error |
Error boundary, logging |
Navigation
Use NavigationMixin with page reference types:
standard__recordPage — view/edit/clone records (requires recordId, actionName)
standard__objectPage — object home/list/new (requires objectApiName, actionName)
standard__namedPage — standard pages (home, chatter, filePreview)
standard__webPage — external URLs (requires url)
Lightning Message Service (LMS)
Cross-DOM communication between LWC, Aura, and Visualforce:
- Define message channel in
.messageChannel-meta.xml
publish(messageContext, channel, payload) to send
subscribe(messageContext, channel, handler, {scope: APPLICATION_SCOPE}) to receive
- Always
unsubscribe() in disconnectedCallback() to prevent memory leaks
Shadow DOM vs Light DOM
- Shadow DOM (default): CSS isolation, encapsulated DOM — use for most components
- Light DOM (
lwc:dom="light"): No encapsulation — use when you need cross-component ARIA references, global CSS, or third-party library DOM access
- Shadow DOM blocks
document.querySelector() from outside — use this.template.querySelector() inside
Rules
- Always use SLDS classes for styling — avoid custom CSS when SLDS has a utility
- Use
@api for public properties, reactive by default
- Use
@wire for declarative data fetching
- Use imperative Apex calls for user-initiated actions
- Handle loading states and errors in every component
- Use
lightning-record-form / lightning-record-edit-form for simple CRUD
- Dispatch custom events for child-to-parent communication
- Use
MessageChannel for cross-DOM communication
Gotchas
@track is deprecated — all properties are reactive by default since API v40+
renderedCallback() fires after EVERY render — always guard with a boolean flag to prevent infinite loops
- LDS cache is NOT automatically refreshed — call
refreshApex(wiredProperty) after imperative mutations
- LMS subscriptions MUST unsubscribe in
disconnectedCallback() to prevent memory leaks
- Shadow DOM blocks ID-based ARIA references (
aria-labelledby) across components — use Light DOM for accessibility
- CSP blocks
eval(), new Function(), and inline <script> — load third-party libraries via loadScript() from Static Resources
@api properties are read-only in the component — parent sets them, child cannot mutate
- Wire adapters re-fire when reactive parameters change — avoid unnecessary parameter changes
Workflow
- Understand the component requirements
- Check for existing components that can be extended
- Generate all bundle files (HTML, JS, CSS, meta.xml)
- Generate Jest test file with mock data
- Deploy:
sf project deploy start -d force-app/main/default/lwc/componentName/
References
- LWC Patterns — LDS, navigation, LMS, datatable, custom events, slots, accessibility, SLDS, third-party libs, dynamic components, Experience Cloud
1---2name: sf-lwc3description: |4 Scaffold Lightning Web Components with HTML templates, JS controllers, CSS5 with SLDS compliance, js-meta.xml config, and Jest tests. Use when asked about6 Lightning Web Components, LWC, component scaffolding, or Jest tests for LWC.7 Activate on .js-meta.xml files, mentions of "LWC", "Lightning Web Component",8 "wire adapter", "lightning component", or "@api/@wire/@track decorators".9license: Apache-2.010compatibility: Requires Salesforce CLI (sf) v2+ and Node.js for Jest tests.11metadata:12 source: https://skillmd.com/skills/clientell-ai/sf-lwc13 author: clientell14 version: "1.0.0"15 tags: salesforce, lwc, lightning-web-components, jest, frontend16# Claude Code specific17allowed-tools: Read,Write,Edit,Bash(sf *),Bash(npm *),Glob,Grep18context: fork19---2021# LWC Scaffolder2223You are a Salesforce Lightning Web Component specialist. Generate complete, production-ready LWC bundles.2425## LWC Bundle Structure26Every LWC consists of these files in `force-app/main/default/lwc/componentName/`:2728```29myComponent/30├── myComponent.html # Template31├── myComponent.js # Controller32├── myComponent.css # Styles (SLDS-compliant)33├── myComponent.js-meta.xml # Configuration34└── __tests__/35 └── myComponent.test.js # Jest tests36```3738## Naming Conventions39- Bundle folder: `camelCase` (e.g., `accountList`)40- HTML markup: `kebab-case` with `c-` namespace (e.g., `<c-account-list>`)41- JS class: `PascalCase` (e.g., `AccountList`)42- CSS: follows component name4344## JavaScript Controller Pattern45```javascript46import { LightningElement, api, wire, track } from 'lwc';47import { ShowToastEvent } from 'lightning/platformShowToastEvent';48import { NavigationMixin } from 'lightning/navigation';49import getRecords from '@salesforce/apex/MyController.getRecords';50import ACCOUNT_NAME from '@salesforce/schema/Account.Name';5152export default class MyComponent extends NavigationMixin(LightningElement) {53 @api recordId;54 @track records = [];55 error;56 isLoading = false;5758 @wire(getRecords, { recordId: '$recordId' })59 wiredRecords({ error, data }) {60 if (data) {61 this.records = data;62 this.error = undefined;63 } else if (error) {64 this.error = error;65 this.records = [];66 }67 }6869 handleAction() {70 this.isLoading = true;71 imperativeMethod({ param: this.recordId })72 .then(result => {73 this.dispatchEvent(new ShowToastEvent({74 title: 'Success',75 message: 'Operation completed',76 variant: 'success'77 }));78 })79 .catch(error => {80 this.dispatchEvent(new ShowToastEvent({81 title: 'Error',82 message: error.body?.message || 'An error occurred',83 variant: 'error'84 }));85 })86 .finally(() => {87 this.isLoading = false;88 });89 }90}91```9293## Meta XML Configuration94```xml95<?xml version="1.0" encoding="UTF-8"?>96<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">97 <apiVersion>62.0</apiVersion>98 <isExposed>true</isExposed>99 <targets>100 <target>lightning__RecordPage</target>101 <target>lightning__AppPage</target>102 <target>lightning__HomePage</target>103 </targets>104 <targetConfigs>105 <targetConfig targets="lightning__RecordPage">106 <objects>107 <object>Account</object>108 </objects>109 <property name="title" type="String" default="My Component"/>110 </targetConfig>111 </targetConfigs>112</LightningComponentBundle>113```114115## Jest Test Pattern116```javascript117import { createElement } from 'lwc';118import MyComponent from 'c/myComponent';119import getRecords from '@salesforce/apex/MyController.getRecords';120121// Mock Apex method122jest.mock('@salesforce/apex/MyController.getRecords', () => ({123 default: jest.fn()124}), { virtual: true });125126const MOCK_DATA = [127 { Id: '001xx000003ABCDEF', Name: 'Test Account' }128];129130describe('c-my-component', () => {131 afterEach(() => {132 while (document.body.firstChild) {133 document.body.removeChild(document.body.firstChild);134 }135 jest.clearAllMocks();136 });137138 it('renders records when data is returned', async () => {139 getRecords.mockResolvedValue(MOCK_DATA);140141 const element = createElement('c-my-component', { is: MyComponent });142 element.recordId = '001xx000003ABCDEF';143 document.body.appendChild(element);144145 await Promise.resolve();146147 const items = element.shadowRoot.querySelectorAll('.record-item');148 expect(items.length).toBe(1);149 });150151 it('shows error when apex call fails', async () => {152 getRecords.mockRejectedValue(new Error('Test error'));153154 const element = createElement('c-my-component', { is: MyComponent });155 document.body.appendChild(element);156157 await Promise.resolve();158159 const errorEl = element.shadowRoot.querySelector('.error-message');160 expect(errorEl).toBeTruthy();161 });162});163```164165### Lightning Data Service (LDS)166Use `lightning/uiRecordApi` for CRUD without Apex:167- `getRecord` wire adapter — read records with field-level security168- `createRecord`, `updateRecord`, `deleteRecord` — imperative CRUD169- `getObjectInfo`, `getPicklistValues` — metadata access170- `refreshApex()` — invalidate wire cache after mutations171- **When to use**: Simple CRUD. Use Apex wire for complex queries or business logic.172173### Lifecycle Hooks174| Hook | When | Common Use |175|------|------|------------|176| `constructor()` | Component created | Initialize state |177| `connectedCallback()` | Inserted into DOM | Fetch data, add listeners |178| `renderedCallback()` | After each render | DOM manipulation (guard with flag!) |179| `disconnectedCallback()` | Removed from DOM | Cleanup listeners, unsubscribe LMS |180| `errorCallback(error, stack)` | Child error | Error boundary, logging |181182### Navigation183Use `NavigationMixin` with page reference types:184- `standard__recordPage` — view/edit/clone records (requires `recordId`, `actionName`)185- `standard__objectPage` — object home/list/new (requires `objectApiName`, `actionName`)186- `standard__namedPage` — standard pages (home, chatter, filePreview)187- `standard__webPage` — external URLs (requires `url`)188189### Lightning Message Service (LMS)190Cross-DOM communication between LWC, Aura, and Visualforce:191- Define message channel in `.messageChannel-meta.xml`192- `publish(messageContext, channel, payload)` to send193- `subscribe(messageContext, channel, handler, {scope: APPLICATION_SCOPE})` to receive194- Always `unsubscribe()` in `disconnectedCallback()` to prevent memory leaks195196### Shadow DOM vs Light DOM197- **Shadow DOM** (default): CSS isolation, encapsulated DOM — use for most components198- **Light DOM** (`lwc:dom="light"`): No encapsulation — use when you need cross-component ARIA references, global CSS, or third-party library DOM access199- Shadow DOM blocks `document.querySelector()` from outside — use `this.template.querySelector()` inside200201## Rules202- Always use SLDS classes for styling — avoid custom CSS when SLDS has a utility203- Use `@api` for public properties, reactive by default204- Use `@wire` for declarative data fetching205- Use imperative Apex calls for user-initiated actions206- Handle loading states and errors in every component207- Use `lightning-record-form` / `lightning-record-edit-form` for simple CRUD208- Dispatch custom events for child-to-parent communication209- Use `MessageChannel` for cross-DOM communication210211## Gotchas212- `@track` is deprecated — all properties are reactive by default since API v40+213- `renderedCallback()` fires after EVERY render — always guard with a boolean flag to prevent infinite loops214- LDS cache is NOT automatically refreshed — call `refreshApex(wiredProperty)` after imperative mutations215- LMS subscriptions MUST unsubscribe in `disconnectedCallback()` to prevent memory leaks216- Shadow DOM blocks ID-based ARIA references (`aria-labelledby`) across components — use Light DOM for accessibility217- CSP blocks `eval()`, `new Function()`, and inline `<script>` — load third-party libraries via `loadScript()` from Static Resources218- `@api` properties are read-only in the component — parent sets them, child cannot mutate219- Wire adapters re-fire when reactive parameters change — avoid unnecessary parameter changes220221## Workflow2221. Understand the component requirements2232. Check for existing components that can be extended2243. Generate all bundle files (HTML, JS, CSS, meta.xml)2254. Generate Jest test file with mock data2265. Deploy: `sf project deploy start -d force-app/main/default/lwc/componentName/`227228## References229- [LWC Patterns](references/lwc-patterns.md) — LDS, navigation, LMS, datatable, custom events, slots, accessibility, SLDS, third-party libs, dynamic components, Experience Cloud