sf-lwc

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

sf-lwc: Lightning Web Components Development

sf-lwc: Lightning Web Components 开发

Expert frontend engineer specializing in Lightning Web Components for Salesforce. Generate production-ready LWC components using the PICKLES Framework for architecture, with proper data binding, Apex/GraphQL integration, event handling, SLDS 2 styling, and comprehensive Jest tests.
专注于Salesforce Lightning Web Components的资深前端工程师。采用PICKLES Framework架构生成可用于生产环境的LWC组件,包含完善的数据绑定、Apex/GraphQL集成、事件处理、SLDS 2样式以及全面的Jest测试。

Core Responsibilities

核心职责

  1. Component Scaffolding: Generate complete LWC bundles (JS, HTML, CSS, meta.xml)
  2. PICKLES Architecture: Apply structured design methodology for robust components
  3. Wire Service Patterns: Implement @wire decorators for data fetching (Apex & GraphQL)
  4. Apex/GraphQL Integration: Connect LWC to backend with @AuraEnabled and GraphQL
  5. Event Handling: Component communication (CustomEvent, LMS, pubsub)
  6. Lifecycle Management: Proper use of connectedCallback, renderedCallback, etc.
  7. Jest Testing: Generate comprehensive unit tests with advanced patterns
  8. Accessibility: WCAG compliance with ARIA attributes, focus management
  9. Dark Mode: SLDS 2 compliant styling with global styling hooks
  10. Performance: Lazy loading, virtual scrolling, debouncing, efficient rendering
  1. 组件脚手架:生成完整的LWC包(JS、HTML、CSS、meta.xml)
  2. PICKLES架构:应用结构化设计方法论构建健壮组件
  3. Wire服务模式:实现@wire装饰器用于数据获取(Apex & GraphQL)
  4. Apex/GraphQL集成:通过@AuraEnabled和GraphQL将LWC与后端连接
  5. 事件处理:组件通信(CustomEvent、LMS、pubsub)
  6. 生命周期管理:合理使用connectedCallback、renderedCallback等钩子
  7. Jest测试:生成具备高级模式的全面单元测试
  8. 可访问性:遵循WCAG标准,添加ARIA属性、管理焦点
  9. 深色模式:符合SLDS 2标准的样式,支持全局样式钩子
  10. 性能优化:懒加载、虚拟滚动、防抖处理、高效渲染

Document Map

文档图谱

NeedDocumentDescription
Component patternsreferences/component-patterns.mdWire, GraphQL, Modal, Navigation, TypeScript
LMS guidereferences/lms-guide.mdLightning Message Service deep dive
Jest testingreferences/jest-testing.mdAdvanced testing patterns
Accessibilityreferences/accessibility-guide.mdWCAG compliance, ARIA, focus management
Performancereferences/performance-guide.mdDark mode migration, lazy loading, optimization
Scoring & testingreferences/scoring-and-testing.md165-point SLDS 2 scoring, dark mode checklist, Jest patterns
Advanced featuresreferences/advanced-features.mdFlow Screen integration, TypeScript, Dashboards, Agentforce
State managementreferences/state-management.md@track, Singleton Store, @lwc/state
Template anti-patternsreferences/template-anti-patterns.mdLLM template mistakes
Async notificationsreferences/async-notification-patterns.mdPlatform Events + empApi
Flow integrationreferences/flow-integration-guide.mdFlow-LWC communication

需求文档描述
组件模式references/component-patterns.mdWire、GraphQL、模态框、导航、TypeScript
LMS指南references/lms-guide.mdLightning Message Service深度解析
Jest测试references/jest-testing.md高级测试模式
可访问性references/accessibility-guide.mdWCAG合规、ARIA、焦点管理
性能优化references/performance-guide.md深色模式迁移、懒加载、优化技巧
评分与测试references/scoring-and-testing.md165分SLDS 2评分、深色模式检查清单、Jest模式
高级功能references/advanced-features.mdFlow Screen集成、TypeScript、仪表盘、Agentforce
状态管理references/state-management.md@track、单例Store、@lwc/state
模板反模式references/template-anti-patterns.mdLLM模板错误示例
异步通知references/async-notification-patterns.md平台事件 + empApi
Flow集成references/flow-integration-guide.mdFlow-LWC通信

PICKLES Framework (Architecture Methodology)

PICKLES Framework (架构方法论)

┌─────────────────────────────────────────────────────────────────────┐
│                     PICKLES FRAMEWORK                                │
├─────────────────────────────────────────────────────────────────────┤
│  P → Prototype    │  Validate ideas with wireframes & mock data    │
│  I → Integrate    │  Choose data source (LDS, Apex, GraphQL, API)  │
│  C → Composition  │  Structure component hierarchy & communication │
│  K → Kinetics     │  Handle user interactions & event flow         │
│  L → Libraries    │  Leverage platform APIs & base components      │
│  E → Execution    │  Optimize performance & lifecycle hooks        │
│  S → Security     │  Enforce permissions, FLS, and data protection │
└─────────────────────────────────────────────────────────────────────┘
PrincipleKey Actions
P - PrototypeWireframes, mock data, stakeholder review, separation of concerns
I - IntegrateLDS for single records, Apex for complex queries, GraphQL for related data
C - Composition
@api
for parent→child, CustomEvent for child→parent, LMS for cross-DOM
K - KineticsDebounce search (300ms), disable during submit, keyboard navigation
L - LibrariesUse
lightning/*
modules, base components, avoid reinventing
E - ExecutionLazy load with
lwc:if
, cache computed values, avoid infinite loops
S - Security
WITH SECURITY_ENFORCED
, input validation, FLS/CRUD checks
For detailed PICKLES implementation patterns, see references/component-patterns.md

┌─────────────────────────────────────────────────────────────────────┐
│                     PICKLES FRAMEWORK                                │
├─────────────────────────────────────────────────────────────────────┤
│  P → Prototype    │  Validate ideas with wireframes & mock data    │
│  I → Integrate    │  Choose data source (LDS, Apex, GraphQL, API)  │
│  C → Composition  │  Structure component hierarchy & communication │
│  K → Kinetics     │  Handle user interactions & event flow         │
│  L → Libraries    │  Leverage platform APIs & base components      │
│  E → Execution    │  Optimize performance & lifecycle hooks        │
│  S → Security     │  Enforce permissions, FLS, and data protection │
└─────────────────────────────────────────────────────────────────────┘
原则关键行动
P - 原型设计线框图、模拟数据、利益相关者评审、关注点分离
I - 集成LDS用于单条记录、Apex用于复杂查询、GraphQL用于关联数据
C - 组件组合
@api
实现父→子通信、CustomEvent实现子→父通信、LMS用于跨DOM通信
K - 交互处理搜索防抖(300ms)、提交时禁用、键盘导航
L - 库利用使用
lightning/*
模块、基础组件,避免重复造轮子
E - 执行优化
lwc:if
懒加载、缓存计算值、避免无限循环
S - 安全保障
WITH SECURITY_ENFORCED
、输入验证、FLS/CRUD检查
如需了解PICKLES的详细实现模式,请查看references/component-patterns.md

Key Component Patterns

核心组件模式

Wire vs Imperative Apex Calls

Wire vs 命令式Apex调用

AspectWire (@wire)Imperative Calls
ExecutionAutomatic / ReactiveManual / Programmatic
DMLRead-OnlyInsert/Update/Delete
Data UpdatesAuto on param changeManual refresh
CachingBuilt-inNone
Quick Decision: Use
@wire
for read-only display with auto-refresh. Use imperative for user actions, DML, or when you need control over timing.
维度Wire (@wire)命令式调用
执行方式自动/响应式手动/程序化
DML操作只读插入/更新/删除
数据更新参数变化时自动更新手动刷新
缓存内置
快速决策:使用
@wire
实现带自动刷新的只读显示。在用户操作、DML操作或需要控制执行时机时使用命令式调用。

Data Source Decision Tree

数据源决策树

ScenarioRecommended Approach
Single record by IDLightning Data Service (
getRecord
)
Simple record CRUD
lightning-record-form
/
lightning-record-edit-form
Complex queriesApex with
@AuraEnabled(cacheable=true)
Related recordsGraphQL wire adapter
Real-time updatesPlatform Events / Streaming API
External dataNamed Credentials + Apex callout
场景推荐方案
通过ID获取单条记录Lightning Data Service (
getRecord
)
简单记录CRUD
lightning-record-form
/
lightning-record-edit-form
复杂查询
@AuraEnabled(cacheable=true)
的Apex
关联记录GraphQL Wire适配器
实时更新平台事件/流API
外部数据命名凭据 + Apex调用

Communication Patterns

通信模式

PatternDirectionUse Case
@api
properties
Parent → ChildPass data down
Custom EventsChild → ParentBubble actions up
Lightning Message ServiceAny → AnyCross-DOM communication
Pub/SubSibling → SiblingSame page, no hierarchy
Decision Tree: Same parent? → Events up,
@api
down. Different DOM trees? → LMS. LWC ↔ Aura/VF? → LMS.
模式方向使用场景
@api
属性
父 → 子向下传递数据
自定义事件子 → 父向上传递操作
Lightning Message Service任意 → 任意跨DOM通信
Pub/Sub兄弟 → 兄弟同页面、无层级关系
决策树:同一父组件下?→ 事件向上、
@api
向下。不同DOM树?→ LMS。LWC与Aura/VF通信?→ LMS。

Lifecycle Hook Guidance

生命周期钩子指南

HookWhen to UseAvoid
constructor()
Initialize propertiesDOM access (not ready)
connectedCallback()
Subscribe to events, fetch dataHeavy processing
renderedCallback()
DOM-dependent logicInfinite loops, property changes
disconnectedCallback()
Cleanup subscriptions/listenersAsync operations

钩子使用时机避免操作
constructor()
初始化属性访问DOM(尚未准备好)
connectedCallback()
订阅事件、获取数据大量计算操作
renderedCallback()
依赖DOM的逻辑无限循环、修改属性
disconnectedCallback()
清理订阅/监听器异步操作

SLDS 2 Validation & Dark Mode

SLDS 2验证与深色模式

See references/scoring-and-testing.md for the full 165-point scoring breakdown, dark mode checklist, styling hooks reference, and Jest testing patterns.
Quick summary: 8 categories, 165 total points. 150+ Production-ready | 125+ Good | 100+ Functional | <75 Needs work. Dark mode requires CSS variables only (
--slds-g-color-*
), no hardcoded colors.

完整的165分评分细则、深色模式检查清单、样式钩子参考以及Jest测试模式,请查看references/scoring-and-testing.md
快速总结:分为8个类别,共165分。150分以上:生产就绪 | 125分以上:良好 | 100分以上:可用 | 低于75分:需要优化。深色模式仅支持CSS变量(
--slds-g-color-*
),禁止硬编码颜色。

Accessibility

可访问性

WCAG compliance is mandatory for all components.
RequirementImplementation
Labels
label
on inputs,
aria-label
on icons
KeyboardEnter/Space triggers, Tab navigation
FocusVisible indicator, logical order, focus traps in modals
Live Regions
aria-live="polite"
for dynamic content
Contrast4.5:1 minimum for text
For comprehensive guide, see references/accessibility-guide.md

所有组件必须符合WCAG标准。
要求实现方式
标签输入框添加
label
、图标添加
aria-label
键盘导航回车/空格触发操作、Tab键导航
焦点管理可见的焦点指示器、合理的顺序、模态框焦点陷阱
实时区域动态内容使用
aria-live="polite"
对比度文本最小对比度4.5:1
如需完整指南,请查看references/accessibility-guide.md

Metadata Configuration

元数据配置

xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>66.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Account Dashboard</masterLabel>
    <description>SLDS 2 compliant account dashboard with dark mode support</description>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
        <target>lightning__FlowScreen</target>
        <target>lightningCommunity__Page</target>
        <target>lightning__Dashboard</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <objects><object>Account</object></objects>
            <property name="title" type="String" default="Dashboard"/>
            <property name="maxRecords" type="Integer" default="10"/>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>66.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Account Dashboard</masterLabel>
    <description>SLDS 2 compliant account dashboard with dark mode support</description>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
        <target>lightning__FlowScreen</target>
        <target>lightningCommunity__Page</target>
        <target>lightning__Dashboard</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <objects><object>Account</object></objects>
            <property name="title" type="String" default="Dashboard"/>
            <property name="maxRecords" type="Integer" default="10"/>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

Flow Screen & Advanced Features

Flow Screen与高级功能

See references/advanced-features.md for Flow Screen integration (FlowAttributeChangeEvent, FlowNavigationFinishEvent), TypeScript support (API 66.0 GA), LWC in Dashboards (Beta), and Agentforce discoverability.
Flow Screen quick reference:
@api
inputs →
FlowAttributeChangeEvent
outputs →
FlowNavigationFinishEvent
for navigation. See also references/flow-integration-guide.md.

Flow Screen集成(FlowAttributeChangeEvent、FlowNavigationFinishEvent)、TypeScript支持(API 66.0正式版)、仪表盘内LWC(测试版)以及Agentforce可发现性的详细内容,请查看references/advanced-features.md
Flow Screen快速参考
@api
输入 →
FlowAttributeChangeEvent
输出 →
FlowNavigationFinishEvent
用于导航。也可查看references/flow-integration-guide.md

CLI Commands

CLI命令

CommandPurpose
sf lightning generate component --type lwc
Create new LWC
sf lightning lwc test run
Run Jest tests
sf lightning lwc test run --watch
Watch mode
sf project deploy start -m LightningComponentBundle
Deploy LWC
bash
undefined
命令用途
sf lightning generate component --type lwc
创建新的LWC组件
sf lightning lwc test run
运行Jest测试
sf lightning lwc test run --watch
监听模式
sf project deploy start -m LightningComponentBundle
部署LWC组件
bash
undefined

Generate new component

Generate new component

sf lightning generate component
--name accountDashboard
--type lwc
--output-dir force-app/main/default/lwc
sf lightning generate component
--name accountDashboard
--type lwc
--output-dir force-app/main/default/lwc

Run tests with coverage

Run tests with coverage

sf lightning lwc test run -- --coverage
sf lightning lwc test run -- --coverage

Specific component tests

Specific component tests

sf lightning lwc test run --spec force-app/main/default/lwc/accountList/tests

---
sf lightning lwc test run --spec force-app/main/default/lwc/accountList/tests

---

Cross-Skill Integration

跨技能集成

SkillUse Case
sf-apexGenerate Apex controllers (
@AuraEnabled
,
@InvocableMethod
)
sf-flowEmbed components in Flow Screens, pass data to/from Flow
sf-testingGenerate Jest tests
sf-deployDeploy components
sf-metadataCreate message channels

技能使用场景
sf-apex生成Apex控制器(
@AuraEnabled
@InvocableMethod
sf-flow在Flow Screen中嵌入组件、与Flow双向传值
sf-testing生成Jest测试
sf-deploy部署LWC组件
sf-metadata创建消息通道

Dependencies

依赖项

Required: Target org with LWC support (API 45.0+),
sf
CLI authenticated For Testing: Node.js 18+, Jest (
@salesforce/sfdx-lwc-jest
) For SLDS Validation:
@salesforce-ux/slds-linter
(optional)

必需:支持LWC的目标组织(API 45.0+)、已认证的
sf
CLI 测试所需:Node.js 18+、Jest(
@salesforce/sfdx-lwc-jest
SLDS验证所需
@salesforce-ux/slds-linter
(可选)

External References

外部参考