### Install and run LWR project Source: https://lwc.dev/guide/install Navigate to your project directory, install dependencies, and start the development server. ```bash cd YourProjectName npm install npm run start ``` -------------------------------- ### Initialize and start an LWR project Source: https://lwc.dev Commands to initialize a new project, install dependencies, and start the development server. ```bash $ npm init lwr $ npm install $ npm run start ``` -------------------------------- ### Initialize LWC project with LWR Source: https://lwc.dev/guide/install Run this command to start the interactive setup for a new Lightning Web Components project using Lightning Web Runtime. ```bash npm init lwr@latest ``` -------------------------------- ### Install Jest and LWC Jest packages Source: https://lwc.dev/guide/test Install Jest and the LWC Jest packages. The first command installs Jest, the second installs the preset package, and the third installs the individual packages if the preset is not used. ```bash npm install jest --save-dev ``` ```bash npm install @lwc/jest-preset --save-dev ``` ```bash npm install @lwc/jest-transformer --save-dev npm install @lwc/jest-resolver --save-dev npm install @lwc/jest-serializer --save-dev ``` -------------------------------- ### Slot Forwarding Setup Source: https://lwc.dev/guide/light_dom Initial setup for passing content from a container into an outer component. ```html ``` -------------------------------- ### Comprehensive @salesforce module fix examples Source: https://lwc.dev/guide/error_codes/lwc1704 Examples of correctly formatted imports for various @salesforce modules. ```javascript // Add resource after module prefix import myLabel from "@salesforce/label/c.MyLabel"; import country from "@salesforce/i18n/country"; import ACCOUNT_OBJECT from "@salesforce/schema/Account"; import getAccounts from "@salesforce/apex/AccountController.getAccounts"; // For refreshApex, use named import without trailing slash import { refreshApex } from "@salesforce/apex"; ``` -------------------------------- ### Install Salesforce Lightning Types Package Source: https://lwc.dev/guide/install Install the @salesforce/lightning-types package using either npm or yarn. ```bash npm install @salesforce/lightning-types # OR yarn add @salesforce/lightning-types ``` -------------------------------- ### Example HTML Template for DOM Querying Source: https://lwc.dev/guide/composition An example HTML template containing slots to be queried by the component. ```html ``` -------------------------------- ### Install Webpack dependencies Source: https://lwc.dev/guide/install Install the necessary packages to build an LWC application using Webpack. ```bash npm install --save-dev webpack webpack-cli lwc-webpack-plugin lwc @lwc/module-resolver ``` -------------------------------- ### Install Rollup dependencies Source: https://lwc.dev/guide/install Install the necessary packages to build an LWC application using Rollup. ```bash npm install --save-dev lwc rollup @lwc/rollup-plugin @rollup/plugin-replace ``` -------------------------------- ### Imperative event listener setup Source: https://lwc.dev/guide/events Setup for imperative event handling including the owner template, child template, and the JavaScript class using renderedCallback to attach the listener. ```html ``` ```html ``` ```javascript // owner.js import { LightningElement } from 'lwc'; export default class App extends LightningElement { renderedCallback(){ this.template.querySelector('example-child').addEventListener('click', this.handleClick); } handleClick(e){ // Your code here } } ``` -------------------------------- ### Example Diagnostic Message Source: https://lwc.dev/guide/error_codes/lwc1010 An example of the LWC1010 error message as it appears in the console. ```text LWC1010: Failed to resolve entry for module "userCard". ``` -------------------------------- ### LWC1116 Diagnostic Examples Source: https://lwc.dev/guide/error_codes/lwc1116 Examples of diagnostic messages triggered by invalid folder names. ```text LWC1116: Illegal folder name "ContactCard". The folder name must start with a lowercase character: "contactCard". ``` ```text LWC1116: Illegal folder name "OrderSummary". The folder name must start with a lowercase character: "orderSummary". ``` -------------------------------- ### Example Diagnostic Messages for LWC1118 Source: https://lwc.dev/guide/error_codes/lwc1118 Three example diagnostic messages showing the error output for different import paths and file names. ```plaintext LWC1118: Failed to resolve "./utils.js" from "test.js". Did you mean "Utils"? ``` ```plaintext LWC1118: Failed to resolve "./lib/helper.js" from "myComponent.js". Did you mean "lib/Helper"? ``` ```plaintext LWC1118: Failed to resolve "./other.html" from "myComponent.js". Did you mean "Other"? ``` -------------------------------- ### LWC1108 Error Example: Public Properties Starting with "on" Source: https://lwc.dev/guide/error_codes/lwc1108 A component class that triggers LWC1108 because it declares @api properties and getters with names starting with "on" (onChange, onClick, onLoad). ```javascript import { api, LightningElement } from 'lwc'; export default class MyComponent extends LightningElement { @api onChange; @api onClick; @api get onLoad() { return this._value; } } ``` -------------------------------- ### Invalid Component Folder Structure Source: https://lwc.dev/guide/error_codes/lwc1116 An example of a component folder structure that triggers LWC1116 due to the starting uppercase letter. ```text ContactCard/ ├── contactCard.js ├── contactCard.html ``` -------------------------------- ### Default export example Source: https://lwc.dev/guide/javascript_share_code Exports a single default function from a module. ```javascript // myFunction.js export default myFunction () { ··· } ``` -------------------------------- ### Public property named dataFooBar causing LWC1107 Source: https://lwc.dev/guide/error_codes/lwc1107 Example of a component class triggering LWC1107 due to an @api property starting with 'data'. ```javascript import { api, LightningElement } from 'lwc'; export default class Test extends LightningElement { @api dataFooBar; } ``` -------------------------------- ### Static Composition Example Components Source: https://lwc.dev/guide/events A set of components demonstrating static composition where c-app composes c-parent, which composes c-child. ```html ``` ```html ``` ```html ``` ```html ``` -------------------------------- ### Example container usage Source: https://lwc.dev/guide/composition Demonstrates passing child components into a container slot, including conditional rendering of child components. ```html ``` -------------------------------- ### Invalid Event Handler Starting with Underscore Source: https://lwc.dev/guide/error_codes/lwc1056 This example triggers LWC1056 because the event handler name 'on_itemselect' has an underscore immediately after the 'on' prefix. ```html ``` -------------------------------- ### Invalid Event Handler Starting with Number Source: https://lwc.dev/guide/error_codes/lwc1056 This example triggers LWC1056 because the event handler name 'on123' has a number immediately after the 'on' prefix. ```html ``` -------------------------------- ### Compiler Setup with experimentalDynamicDirective Source: https://lwc.dev/guide/error_codes/lwc1130 Shows how to configure the LWC compiler with the experimentalDynamicDirective option enabled, which is required for using lwc:dynamic. ```javascript import { transformSync } from '@lwc/compiler'; const result = transformSync(source, filename, { experimentalDynamicDirective: true, // ... other options }); ``` -------------------------------- ### Module structure example Source: https://lwc.dev/guide/javascript_share_code Shows the directory structure for a shared JavaScript module in a namespace. ```text mynamespace └──myLibrary └──myLibrary.js ``` -------------------------------- ### Corrected Event Handler Starting with Lowercase Letter Source: https://lwc.dev/guide/error_codes/lwc1056 This example resolves LWC1056 by ensuring the character immediately following the 'on' prefix is a lowercase letter. ```html ``` -------------------------------- ### Complete hello.test.js test file Source: https://lwc.dev/guide/test A full example of a Jest test file for the hello component, demonstrating component creation, DOM manipulation, and assertion. ```javascript // hello.test.js import { createElement } from 'lwc'; import Hello from 'c/hello'; describe('example-hello', () => { afterEach(() => { // The jsdom instance is shared across test cases in a single file so reset the DOM while (document.body.firstChild) { document.body.removeChild(document.body.firstChild); } }); it('displays greeting', () => { // Create element const element = createElement('example-hello', { is: Hello, }); document.body.appendChild(element); // Verify displayed greeting const div = element.shadowRoot.querySelector('div'); expect(div.textContent).toBe('Hello, World!'); }); }); ``` -------------------------------- ### Public getter/setter pair named dataInfo causing LWC1107 Source: https://lwc.dev/guide/error_codes/lwc1107 Example of a component class triggering LWC1107 due to an @api getter/setter pair starting with 'data'. ```javascript import { api, LightningElement } from 'lwc'; export default class MyComponent extends LightningElement { _dataInfo; @api get dataInfo() { return this._dataInfo; } set dataInfo(value) { this._dataInfo = value; } } ``` -------------------------------- ### LWC1124 diagnostic messages for invalid attribute names Source: https://lwc.dev/guide/error_codes/lwc1124 Example diagnostic messages for LWC1124. The first shows an attribute starting with a digit (2_under), the second shows a non-ASCII character (ñana). Both are reported on the x-button element. ```text LWC1124: 2_under is not valid attribute for x-button. Attribute name must start with an underscore, dollar sign, or an optional hyphen character followed by an alphabetic character. ``` ```text LWC1124: ñana is not valid attribute for x-button. Attribute name must start with an underscore, dollar sign, or an optional hyphen character followed by an alphabetic character. ``` -------------------------------- ### Render LWC component on server with renderComponent Source: https://lwc.dev/guide/ssr Renders an LWC component on the server using renderComponent from @lwc/ssr-runtime. The example uses express.js to handle a GET request, passing a name query parameter (defaulting to 'World') as a prop. The output markup shows the server-rendered component with its shadow root and a button. ```javascript import { renderComponent } from '@lwc/ssr-runtime'; import App from 'x/App'; // Example using express.js app.get("/ssr-app", (req, res) => { const name = req.query.name || 'World'; const ssrRenderedApp = renderComponent('x-app', App, { name }); return res.send(ssrRenderedApp); }); ``` ```html #shadowRoot Hello World ``` -------------------------------- ### Book List App: app.html, bookEdit.html, bookEdit.js, bookApi.js, server.js Source: https://lwc.dev/guide/wire_adapter The Book List app example includes the main app template, the book-edit component template and logic, the wire adapter definitions, and a server abstraction. The app template wires together book-create, book-list, and book-edit components. The book-edit component uses the getBook wire adapter to load a book by ID and dispatches saveedit and canceledit events. The bookApi.js file defines the getBooks and getBook wire adapters and functions to create, delete, and update books. The server.js file provides a BookEndpoint class that simulates a server with a Map-based store. ```html ``` ```html ``` ```javascript // bookEdit.js import { LightningElement, api, wire } from 'lwc'; import { getBook } from 'c/bookApi'; export default class BookEdit extends LightningElement { @api bookId; draftTitle = ""; @wire(getBook, { id: '$bookId'}) bookDetails(book) { if (book === null) { console.error("Book with id %s does not exist", this.bookId); } this.draftTitle = book.title; }; handleTitleChange(event) { this.draftTitle = event.target.value; } handleSave() { this.dispatchEvent( new CustomEvent('saveedit', { detail: { id: this.bookId, title: this.draftTitle } }) ); } handleCancel() { this.draftTitle = ""; this.dispatchEvent( new CustomEvent('canceledit') ); } } ``` ```javascript // bookApi.js import { bookEndpoint } from './server'; const getBooksInstances = new Set(); function refreshGetBooksInstances() { getBooksInstances.forEach(instance => instance._refresh()); } export class getBooks { constructor(dataCallback) { this.dataCallback = dataCallback; this.dataCallback(); } connect() { getBooksInstances.add(this); } disconnect() { getBooksInstances.remove(this); } update() { this._refresh(); } _refresh() { const allBooks = bookEndpoint.getAll(); this.dataCallback(allBooks); }; } export class getBook { connected = false; bookId; constructor(dataCallback) { this.dataCallback = dataCallback; } connect() { this.connected = true; this.provideBookWithId(this.bookId); } disconnect() { this.connected = false; } update(config) { if (this.bookId !== config.id) { this.bookId = config.id; this.provideBookWithId(this.bookId); } } providBookWithId(id) { if (this.connected && this.bookId !== undefined) { const book = bookEndpoint.getById(id); if (book) { this.dataCallback(Object.assign({}, book)); } else { this.dataCallback(null); } } } } export function createBook(title) { bookEndpoint.create(title); refreshGetBooksInstances(); } export function deleteBook(id) { bookEndpoint.remove(id); refreshGetBooksInstances(); } export function updateBook(id, newTitle) { bookEndpoint.update(id, newTitle); refreshGetBooksInstances(); } ``` ```javascript // server.js // A server abstraction class BookEndpoint { bookStore = new Map(); nextBookId = 0; getAll() { return this.bookStore.values() } getById(id) { return this.bookStore.get(parseInt(id)); } create(title) { const book = { id: this.nextBookId++, title, }; this.bookStore.set(book.id, book); } update(id, title) { const book = { id: parseInt(id), title }; this.bookStore.set(book.id, book); } remove(id) { this.bookStore.delete(parseInt(id)); } } export const bookEndpoint = new BookEndpoint(); bookEndpoint.create('The Way of Kings'); ``` -------------------------------- ### Light DOM vs Shadow DOM Example Source: https://lwc.dev/guide/composition Shows the boundary between light DOM and shadow DOM from different perspectives. ```HTML

I'm a paragraph element, part of the light DOM

#shadow-root |

| In c-child, I'm light DOM. | To everyone else, I'm shadow DOM. |

``` -------------------------------- ### Diagnostic Message Examples Source: https://lwc.dev/guide/error_codes/lwc1119 Examples of the LWC1119 error message format. ```text LWC1119: Failed to resolve @wire adapter "getRecord". Ensure it is imported. ``` ```text LWC1119: Failed to resolve @wire adapter "undefinedAdapter". Ensure it is imported. ``` -------------------------------- ### Component directory structure with tests Source: https://lwc.dev/guide/test Example project structure showing the placement of test files within the __tests__ directory of a component bundle. ```text src ├── modules │ └── foo │ └── todoList │ ├── __tests__ │ │ └── todoList.test.js │ │ └── todoList.ssr-test.js │ ├── todoList.html │ └── todoList.js └── main.js ``` -------------------------------- ### Example Diagnostic Message Source: https://lwc.dev/guide/error_codes/lwc1201 A concrete example of the LWC1201 diagnostic message. ```text LWC1201: The slot attribute in will be ignored due to its ancestor
. It must be a direct child of the containing component. ``` -------------------------------- ### Component Bundle Directory Structure Source: https://lwc.dev/guide/reference Example of a standard LWC component bundle folder structure, including the required HTML, JS, and CSS files, as well as test files. ```text mynamespace └──myComponent ├──__tests__ | └──myComponent.test.js ├──myComponent.html ├──myComponent.js ├──shareCode.js └──myComponent.css ``` -------------------------------- ### Diagnostic Message Example Source: https://lwc.dev/guide/error_codes/lwc1100 Example of the LWC1100 diagnostic message output. ```text LWC1100: Invalid decorator usage. Supported decorators (api, wire, track) should be imported from "lwc" ``` -------------------------------- ### Create Rollup application entry point Source: https://lwc.dev/guide/install Define the entry point in src/main.js to mount the LWC application. ```javascript import { createElement } from 'lwc'; import App from 'x/app'; const elm = createElement('x-app', { is: App }); document.body.appendChild(elm); ``` -------------------------------- ### Diagnostic Message Examples Source: https://lwc.dev/guide/error_codes/lwc1074 Examples of the diagnostic messages produced by LWC1074. ```text Invalid expression {exp1;exp2} - LWC1074: Multiple expressions found ``` ```text Invalid expression {exp;} - LWC1074: Multiple expressions found ``` -------------------------------- ### Diagnostic Message Example Source: https://lwc.dev/guide/error_codes/lwc1034 An example of the LWC1034 diagnostic message output. ```text LWC1034: Ambiguous attribute value title="{myValue}". If you want to make it a valid identifier you should remove the surrounding quotes title={myValue}. If you want to make it a string you should escape it title="\{myValue}". ``` -------------------------------- ### Diagnostic Message Examples Source: https://lwc.dev/guide/error_codes/lwc1011 Examples of the LWC1011 error message format. ```text LWC1011: Failed to resolve import "./utils" from "myComponent.js". Please add "utils" file to the component folder. ``` ```text LWC1011: Failed to resolve import "../sharedUtils" from "myComponent.js". Please add "../sharedUtils" file to the component folder. ``` -------------------------------- ### Replicate configuration in JavaScript Source: https://lwc.dev/guide/error_codes/lwc1005 Fix the metadata import error by moving configuration data into a standard JavaScript file. ```javascript // componentConfig.js export const API_VERSION = 62; export const IS_EXPOSED = true; ``` ```javascript import { LightningElement } from 'lwc'; import { API_VERSION } from './componentConfig.js'; export default class MyComponent extends LightningElement { version = API_VERSION; } ``` -------------------------------- ### Valid attribute name starting with underscore in LWC template Source: https://lwc.dev/guide/error_codes/lwc1124 Corrected LWC template that resolves LWC1124 by renaming the attribute to start with an underscore (_col-under), which is a valid starting character. ```html ``` -------------------------------- ### Import Salesforce Lightning Types Source: https://lwc.dev/guide/install Example of importing a specific Salesforce Lightning type after configuration. ```typescript import LightningInput from "lightning/input"; ``` -------------------------------- ### Clone the LWC Recipes Repository Source: https://lwc.dev/guide/install Use these commands to download the LWC recipes repository to your local machine. ```bash git clone https://github.com/trailheadapps/lwc-recipes-oss.git cd lwc-recipes-oss ``` -------------------------------- ### Diagnostic Message Example Source: https://lwc.dev/guide/error_codes/lwc1021 Example of the error message format returned by the compiler. ```text LWC1021: Expected a boolean value or 'inline' for outputConfig.sourcemap, received "invalid". ``` -------------------------------- ### Light DOM event propagation example Source: https://lwc.dev/guide/light_dom A set of components demonstrating how events bubble through nested Light DOM components. ```html ``` ```html ``` ```html ``` ```javascript // lightChild.js import { LightningElement } from 'lwc'; export default class LightChild extends LightningElement { static renderMode = 'light'; handleClick(event) { this.dispatchEvent( new CustomEvent('buttonclick', { bubbles: true, composed: false } ) ); } } ``` -------------------------------- ### Example Diagnostic Messages Source: https://lwc.dev/guide/error_codes/lwc1144 Common examples of LWC1144 warning messages generated during compilation. ```text LWC1144: Invalid HTML detected, "" was automatically inserted within ""; the compiled template may not match the template source. LWC1144: Invalid HTML detected, "
" was automatically inserted within "