GitHub Copilot LWC 指令指南:基于 awesome-copilot 的 Salesforce Lightning Web Components 开发规范
发布时间:2026/9/11 21:15:47 锦皓数字建站

GitHub Copilot LWC 指令指南基于 awesome-copilot 的 Salesforce Lightning Web Components 开发规范【免费下载链接】awesome-copilotCommunity-contributed instructions, agents, skills, and configurations to help you make the most of GitHub Copilot.项目地址: https://gitcode.com/GitHub_Trending/aw/awesome-copilot本篇技术指南以 awesome-copilot 仓库中的 lwc.instructions.md 为核心系统梳理 Lightning Web ComponentsLWC在 Salesforce Platform 上的开发规范与最佳实践从组件目录结构、Lightning 基础组件选型、SLDS 设计系统合规到响应式属性、wire 数据访问、错误处理、性能优化与可访问性。读完本文你将掌握一套可落地的 LWC 工程规范并能在 GitHub Copilot 中借助本仓库的 salesforce-aura-lwc Agent 与 salesforce-component-standards Skill 自动执行这些检查。指令文件的定位与生效范围本指南的源文件是仓库中的一份 Copilot 指令文档其 YAML frontmatter 定义了它在编辑器中的自动加载范围description: Guidelines and best practices for developing Lightning Web Components (LWC) on Salesforce Platform. applyTo: force-app/main/default/lwc/**description声明该指令用于 Salesforce 平台上 LWC 开发的指南与最佳实践供 Copilot 理解适用场景applyTo限定指令生效的路径范围——只有位于force-app/main/default/lwc/**下的文件才会自动加载这些规则从而保证规范不会误伤其他目录如 Apex 或 Visualforce 文件。从仓库结构看这份指令与 salesforce-aura-lwc.agent.md、salesforce-expert.agent.md 共同构成指令 专用 Agent 质量 Skill的三层体系指令负责告诉 Copilot「怎么写」Agent 负责「按什么流程和检查项交付」Skill 负责「逐条复核质量门禁」。三者都强调同一核心立场——新组件一律优先 LWCAura 仅用于 Aura-only 场景。组件目录结构与文件约定LWC 的工程组织方式与 Aura 不同每个组件拥有独立的文件夹文件夹名必须与组件名一致采用 camelCase 命名例如组件myComponent对应myComponent文件夹。这是 Salesforce CLI 部署与 Copilot 生成代码的基本前提。一个标准组件目录应包含文件是否必需作用myComponent.html必需HTML 模板文件myComponent.js必需JavaScript 控制器文件myComponent.js-meta.xml必需元数据配置文件定义 target、apiVersion 等myComponent.css可选组件专属样式myComponent.test.js可选Jest 单元测试仓库中的 salesforce-aura-lwc.agent.md 进一步把这一约定上升为交付标准实现模式下要求产出完整组件包.html、.js、.css、.js-meta.xml与 Jest 测试并强调凡是处理用户交互或 Apex 数据的组件必须有 Jest 测试文件。核心原则一优先使用 Lightning 基础组件规范第一条原则是一致性、可访问性与未来兼容性优先因此模板中应始终使用 LWC 基础组件库lightning-*而不是原生 HTML 元素。基础组件内置了 SLDS 2、暗色模式支持与无障碍行为仓库的 salesforce-component-standards 明确指出基础组件自带 SLDS 2、暗色模式与可访问性不要重复实现它们的行为。推荐写法!-- Use Lightning components -- lightning-button labelSave variantbrand onclick{handleSave}/lightning-button lightning-input typetext labelName value{name} onchange{handleNameChange}/lightning-input lightning-combobox labelType options{typeOptions} value{selectedType}/lightning-combobox lightning-radio-group nameduration labelDuration options{durationOptions} value{duration} typeradio/lightning-radio-group应避免的原生写法!-- Avoid these -- button onclick{handleSave}Save/button input typetext onchange{handleNameChange} / select onchange{handleTypeChange} option valueoption1Option 1/option /select原生button、input、select缺少平台内置的样式令牌、暗色模式适配与键盘可访问性在 Flow 屏幕组件等场景下还可能造成事件无法到达运行时的兼容问题。salesforce-flow-design 对 Screen Flow 有同样要求用户输入一律使用lightning-input与 SLDS 合规组件不要使用 HTML 表单元素。HTML 元素 → Lightning 组件映射表为方便速查指令文档给出完整的映射关系这是 Copilot 生成代码时最常用的对照表HTML ElementLightning ComponentKey Attributesbuttonlightning-buttonvariant,label,icon-nameinputlightning-inputtype,label,variantselectlightning-comboboxoptions,value,placeholdertextarealightning-textarealabel,max-lengthinput typecheckboxlightning-input typecheckboxchecked,labelinput typeradiolightning-radio-groupoptions,type,nameinput typetogglelightning-input typetogglechecked,variantCustom pillslightning-pilllabel,name,onremoveIconslightning-iconicon-name,size,variant注意映射表中的关键差异select对应lightning-combobox而非lightning-select单选组应使用lightning-radio-group开关对应lightning-input typetoggle。这些差异正是 AI 生成代码时最常见的错误点指令通过显式映射避免此类偏差。核心原则二SLDSLightning Design System合规使用带slds-var-前缀的工具类现代实现应使用带slds-var-前缀的 SLDS 工具类基于 spacing/typography 设计令牌的变量版本而不是过时的固定值类!-- Spacing -- div classslds-var-m-around_medium slds-var-p-top_large div classslds-var-m-bottom_smallContent/div /div !-- Layout -- div classslds-grid slds-wrap slds-gutters_small div classslds-col slds-size_1-of-2 slds-medium-size_1-of-3 !-- Content -- /div /div !-- Typography -- h2 classslds-text-heading_medium slds-var-m-bottom_smallSection Title/h2 p classslds-text-body_regularDescription text/p布局建议遵循 12 列栅格slds-size_1-of-2、slds-medium-size_1-of-3等slds-*_size_*负责移动端、slds-medium-*前缀负责平板及以上断点的响应式行为。标准 SLDS 组件模式以下两个模式覆盖了大多数业务 UI 场景——卡片容器与堆叠表单!-- Card Layout -- article classslds-card slds-var-m-around_medium header classslds-card__header h2 classslds-text-heading_smallCard Title/h2 /header div classslds-card__body slds-card__body_inner !-- Card content -- /div footer classslds-card__footer !-- Card actions -- /footer /article !-- Form Layout -- div classslds-form slds-form_stacked div classslds-form-element lightning-input labelField Label value{fieldValue}/lightning-input /div /div从仓库的 Agent 规范看SLDS 合规不只是样子好看salesforce-aura-lwc.agent.md 的 PICKLES 检查清单中Look维度要求使用 SLDS 2 令牌与基础组件而非硬编码样式并明确优先使用lightning-card、lightning-layout、lightning-tile代替手工拼装的布局 div——这说明手写slds-card结构在某些场景仍必要但能由基础组件替代时如lightning-card应优先基础组件。核心原则三避免自定义 CSS用 SLDS 语义类表达状态颜色与主题语义应直接使用 SLDS 提供的状态类而不是自造样式!-- Color and theming -- div classslds-theme_success slds-text-color_inverse slds-var-p-around_small Success message /div div classslds-theme_error slds-text-color_inverse slds-var-p-around_small Error message /div div classslds-theme_warning slds-text-color_inverse slds-var-p-around_small Warning message /div反模式覆写 SLDS 的自定义样式/* Dont create custom styles that override SLDS */ .custom-button { background-color: red; padding: 10px; } .my-special-layout { display: flex; justify-content: center; }硬编码颜色与手工 flex 布局会破坏 SLDS 2 的暗色模式与主题系统。salesforce-component-standards 给出了更严格的两条红线禁止硬编码十六进制颜色color: #FF3366应改为var(--slds-c-button-brand-color-background)等语义令牌禁止用!important覆写 SLDS 类——应当用自定义 CSS 属性组合而不是覆盖。必须使用自定义 CSS 时的规则当确实需要自定义样式时遵循三条准则尽可能使用 CSS 自定义属性设计令牌自定义类名加组件前缀以避免冲突绝不覆写 SLDS 基础类。/* Custom CSS example */ .my-component-special { border-radius: var(--lwc-borderRadiusMedium); box-shadow: var(--lwc-shadowButton); }组件架构最佳实践响应式属性ReactivityLWC 的响应式机制是理解本节的钥匙指令文档用大量注释说明了track的适用边界可以归纳为三条规则原始类型string、number、boolean属性天然响应式——重新赋值即触发重渲染无需任何装饰器复杂对象/数组仅在原地修改mutation时才需要track优先使用不可变immutable更新模式创建新引用替代原地修改从而彻底绕开track。import { LightningElement, track, api } from lwc; export default class MyComponent extends LightningElement { // Use api for public properties api recordId; api title; // Primitive properties (string, number, boolean) are automatically reactive // No decorator needed - reassignment triggers re-render simpleValue initial; count 0; // Computed properties get displayName() { return this.name ? Hello, ${this.name} : Hello, Guest; } // track is NOT needed for simple property reassignment // This will trigger reactivity automatically: handleUpdate() { this.simpleValue updated; // Reactive without track this.count; // Reactive without track } // track IS needed when mutating nested properties without reassignment track complexData { user: { name: John, preferences: { theme: dark } } }; handleDeepUpdate() { // Requires track because were mutating a nested property this.complexData.user.preferences.theme light; } // BETTER: Avoid track by using immutable patterns regularData { user: { name: John, preferences: { theme: dark } } }; handleImmutableUpdate() { // No track needed - were creating a new object reference this.regularData { ...this.regularData, user: { ...this.regularData.user, preferences: { ...this.regularData.user.preferences, theme: light } } }; } // Arrays: track is needed only for mutating methods track items [a, b, c]; handleArrayMutation() { // Requires track this.items.push(d); this.items[0] z; } // BETTER: Use immutable array operations regularItems [a, b, c]; handleImmutableArray() { // No track needed this.regularItems [...this.regularItems, d]; this.regularItems this.regularItems.map((item, idx) idx 0 ? z : item ); } // Use track only for complex objects/arrays when you mutate nested properties. // For example, updating complexObject.details.status without reassigning complexObject. track complexObject { details: { status: new } }; }结合 salesforce-component-standards 的补充规则还有两点值得注意track装饰器未来将成为显式导入LWC 已计划其用法演进且在renderedCallback中设置响应式属性会触发再渲染——必须用守卫变量防止无限渲染循环这一要求与下文性能优化章节的renderedCallback守卫相互呼应。事件处理模式组件间通信遵循严格的方向约定salesforce-component-standards 1.5 节方向机制父 → 子api属性或api方法子 → 父CustomEventthis.dispatchEvent(new CustomEvent(...))兄弟/无关联组件Lightning Message ServiceLMS禁止document.querySelector、window.*、Pub/Sub 库// Custom event dispatch handleSave() { const saveEvent new CustomEvent(save, { detail: { recordData: this.recordData, timestamp: new Date() } }); this.dispatchEvent(saveEvent); } // Lightning component event handling handleInputChange(event) { const fieldName event.target.name; const fieldValue event.target.value; // For lightning-input, lightning-combobox, etc. this[fieldName] fieldValue; } handleRadioChange(event) { // For lightning-radio-group this.selectedValue event.detail.value; } handleToggleChange(event) { // For lightning-input typetoggle this.isToggled event.detail.checked; }注意不同基础组件的取值入口差异lightning-input/lightning-combobox可通过event.target.name/value获取而lightning-radio-group与lightning-input typetoggle需要从event.detail读取。另外salesforce-aura-lwc.agent.md 特别提示作为 Flow 屏幕组件的自定义事件必须设置bubbles: true必要时composed: true否则事件永远无法到达 Flow 运行时。数据访问与 wire 服务数据访问的首选模式是wire适配器它由 Lightning Data ServiceLDS支撑具备缓存与响应式特性参数变化自动重新触发。salesforce-component-standards 的 1.1 节给出了完整选型决策表可作为 Copilot 生成数据访问代码时的决策依据场景模式说明响应式读取单条记录跟随导航wire(getRecord, { recordId, fields })LDS缓存 响应式单对象标准 CRUD 表单lightning-record-form/lightning-record-edit-form内置 FLS、CRUD 与无障碍复杂服务端查询/过滤列表wire(apexMethodName, { param })cacheabletrue允许缓存参数变化重新触发用户主动触发、DML 或不可缓存调用命令式imperativeApex 调用DML 方法不能声明为 cacheable无共享父级的跨组件通信Lightning Message ServiceLMS解耦跨 DOM 边界多对象关联图谱GraphQLwire(gql, { query, variables })单次往返获取复杂关联数据使用 wire 访问记录数据import { getRecord } from lightning/uiRecordApi; import { getObjectInfo } from lightning/uiObjectInfoApi; const FIELDS [Account.Name, Account.Industry, Account.AnnualRevenue]; export default class MyComponent extends LightningElement { api recordId; wire(getRecord, { recordId: $recordId, fields: FIELDS }) record; wire(getObjectInfo, { objectApiName: Account }) objectInfo; get recordData() { return this.record.data ? this.record.data.fields : {}; } }两个关键细节$recordId中的$前缀声明了响应式参数绑定api recordId变化时 wire 自动重跑get recordData通过数据存在性守卫this.record.data ? ... : {}避免未就绪时报错。命令式 Apex 的适用边界指令文档的 Common Anti-Patterns 明确能wire就不命令式调用。但从决策表可见存在两类必须命令式的场景用户主动触发的操作按钮点击、提交表单与DML/不可缓存服务端调用。原因是平台约束——AuraEnabled方法只有cacheabletrue才能被 wire 适配器使用而cacheabletrue的方法不允许执行 DML。salesforce-aura-lwc.agent.md 的反模式表直接点名了这种错误在 DML 方法上使用wire适配器会被平台拦截。错误处理与用户体验规范要求组件具备完整的错误边界异步操作期间展示加载态成功/失败均向用户反馈且所有失败路径必须可读。import { ShowToastEvent } from lightning/platformShowToastEvent; export default class MyComponent extends LightningElement { isLoading false; error null; async handleAsyncOperation() { this.isLoading true; this.error null; try { const result await this.performOperation(); this.showSuccessToast(); } catch (error) { this.error error; this.showErrorToast(error.body?.message || An error occurred); } finally { this.isLoading false; } } performOperation() { // Developer-defined async operation } showSuccessToast() { const event new ShowToastEvent({ title: Success, message: Operation completed successfully, variant: success }); this.dispatchEvent(event); } showErrorToast(message) { const event new ShowToastEvent({ title: Error, message: message, variant: error, mode: sticky }); this.dispatchEvent(event); } }要点拆解三态管理isLoading加载中、error失败信息、成功 toast完成反馈缺一不可错误信息降级error.body?.message || An error occurred处理平台错误对象缺失的兜底场景mode: sticky错误 toast 使用 sticky 模式确保用户不会错过失败信息finally清理加载态无论成败都复位isLoading避免界面卡死在 spinner。仓库的 Agent 规范将这一要求扩展到了测试层面Jest 测试必须覆盖错误态渲染而不仅是 happy pathsalesforce-component-standards 的测试清单中明确列出apex 调用失败时展示错误状态这条用例。性能优化条件渲染指令性能优化的首选手段是条件渲染指令而非 JS 中手动拼接/操作 DOM。规范要求新组件使用lwc:if/lwc:elseif/lwc:elseAPI v58.0旧式if:true/if:false虽仍受支持但新组件应避免使用。现代写法推荐!-- Use template directives for conditional rendering -- template lwc:if{isLoading} lightning-spinner alternative-textLoading.../lightning-spinner /template template lwc:elseif{error} div classslds-theme_error slds-text-color_inverse slds-var-p-around_small {error.message} /div /template template lwc:else template for:each{items} for:itemitem div key{item.id} classslds-var-m-bottom_small {item.name} /div /template /template注意列表渲染的两个配套要素for:eachfor:item定义迭代且每个迭代根元素必须提供唯一的key{item.id}否则平台会告警或渲染异常。旧式写法新组件应避免!-- Legacy approach (avoid in new components) -- template if:true{isLoading} lightning-spinner alternative-textLoading.../lightning-spinner /template template if:true{error} div classslds-theme_error slds-text-color_inverse slds-var-p-around_small {error.message} /div /template template if:false{isLoading} template if:false{error} template for:each{items} for:itemitem div key{item.id} classslds-var-m-bottom_small {item.name} /div /template /template /template对比可见旧式写法需要嵌套的if:false才能表达else语义可读性与可维护性都更差lwc:elseif则把加载中 / 出错 / 正常列表三种状态扁平化表达。性能层面的其他要求来自 salesforce-component-standards 1.6 节还包括connectedCallback中禁止副作用每次 DOM attach 都会执行、renderedCallback必须用布尔守卫防止无限渲染循环、大结果集不得整体存入组件状态应分页或流式处理。可访问性最佳实践可访问性是不可妥协的质量门禁WCAG 2.1 AA。规范给出的核心示范是语义化结构 显式 ARIA 标注 辅助文本!-- Use semantic structure -- section aria-labelProduct Selection h2 classslds-text-heading_mediumProducts/h2 lightning-input typesearch labelSearch Products placeholderEnter product name... aria-describedbysearch-help /lightning-input div idsearch-help classslds-assistive-text Type to filter the product list /div /section要点aria-label为section提供语义名aria-describedbysearch-help将帮助文本与输入框关联辅助技术可读出提示slds-assistive-text让提示文本对屏幕阅读器可见、对视觉用户隐藏显式label而非仅用placeholder作为唯一标签——salesforce-component-standards 的可访问性清单明确禁止placeholder 作为唯一标签。仓库 Agent 补充的可访问性硬性要求salesforce-aura-lwc.agent.md包括所有交互控件必须键盘可达Tab、Enter、Space、Escape所有图标按钮必须有alternative-text或aria-label颜色不能是传达状态的唯一手段必须配合文字、图标或 ARIA 属性错误消息通过aria-describedby与输入框关联。这些与指令文档共同构成组件未达 WCAG 2.1 AA 即视为未完成的质量底线。常见反模式清单指令文档以硬性禁止收尾以下是完整的反模式对照反模式规范要求直接 DOM 操作禁止document.querySelector()及同类 APIjQuery 或外部库避免非 Lightning 兼容的库内联样式使用 SLDS 类而非style属性全局 CSS所有样式必须限定在组件作用域内硬编码值使用自定义标签、自定义元数据或常量命令式 API 调用能用wire就不用命令式import调用内存泄漏在disconnectedCallback()中清理事件监听器agents/salesforce-aura-lwc.agent.md 的反模式表为其中几条补充了具体风险与修复方向最值得注意的包括用innerHTML渲染用户数据是 XSS 漏洞必须改用模板{expression}绑定框架自动转义自定义事件缺bubbles: true时 Flow 屏幕组件收不到事件缺失aria-*属性造成 WCAG 违例。这些反模式同时也是 Code Review 模式下 Agent 的逐条审计项。在 Copilot 工作流中落地这些规范本仓库为上述规范提供了完整的工程化载体可以在日常开发中组合使用安装 Salesforce 开发插件通过 salesforce-development 插件 一次性获得 Apex、Flow、LWC/Aura、Visualforce 四类专用 Agent安装命令为copilot plugin install salesforce-developmentawesome-copilot切换专用 Agent 编写组件构建 LWC UI 时切换到salesforce-aura-lwcAgent详见 salesforce-aura-lwc.agent.md它会按 PICKLES 维度Prototype、Integrate、Compose、Keyboard、Look、Execute、Secure逐项检查并在交付时按固定格式汇报数据访问模式、可访问性措施、SLDS 令牌使用与 Jest 测试覆盖用质量 Skill 做终审对已写或已审查的组件运行 salesforce-component-standards 的逐条检查数据访问模式、XSS 防护、FLS/CRUD、SLDS 2、WCAG 2.1 AA、Jest 覆盖其反模式速查表可作为团队 Code Review 的 checklistAura → LWC 迁移对存量 Aura 组件参考 salesforce-expert.agent.md 的迁移映射——v:attributes→api属性、aura:registerEvent→ 标准 DOMCustomEvent、Data Service 标签 →wire(getRecord)并优先用lightning-record-edit-form替代命令式 Apex 控制器。这套指令约束写法 Agent 保证流程 Skill 强制质量门禁的组合正是 awesome-copilot 社区沉淀出的可复现的 LWC 工程规范。开发者既可以将其作为人工编码的对照清单也可以直接让 Copilot 在force-app/main/default/lwc/**路径下自动遵循从而把上述全部最佳实践固化到每一次代码生成中。【免费下载链接】awesome-copilotCommunity-contributed instructions, agents, skills, and configurations to help you make the most of GitHub Copilot.项目地址: https://gitcode.com/GitHub_Trending/aw/awesome-copilot创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
锦
锦皓数字建站
深耕本土企业品牌数字化升级,专注原创端正雅致商务官网,从视觉设计到稳定运维全程保驾护航。