Skip to main content

Create a Lightning Web Component

In this step you will learn how to use the tools that you installed before.

Create a Salesforce DX Project

The basic foundation for interacting with an org using Salesforce CLI is a Salesforce DX project. A project consists of several local configuration files, as well as the code you want to deploy. In Salesforce terms we call this code metadata, which is the foundation of the Salesforce Platform. If you're new to Salesforce, check out the Platform Developer Beginner trail to learn more about our metadata-driven approach.

We'll use Visual Studio Code to create a project.

  1. Open Visual Studio Code.
  2. Press Command + Shift + P on macOS or Ctrl + Shift + P on Windows or Linux, then type create project. Select SFDX: Create Project, and press Enter.
  3. Leave the default project type selection Standard as is, and press Enter.
  4. Enter trailhead as project name, and press Enter.
  5. Choose a directory on your local machine where the project will be stored. Click Create Project.

Great! You've created your first Salesforce DX project for working with Lightning Web Components. Visual Studio Code will automatically open the new project for you.

Authorize Your Dev Hub

The next step is to authenticate Dev Hub. If you're using a Trailhead Playground you can learn in Get Your Trailhead Playground Username and Password how to get the credentials for the next step.

  1. In Visual Studio Code, press Command + Shift + P on macOS or Ctrl + Shift + P on Windows or Linux.
  2. Type sfdx.
  3. Select SFDX: Authorize a Dev Hub.
  4. Log in using your Dev Hub org credentials.
  5. Click Allow.

    Dev Hub authentication screen
  6. After you authenticate in the browser, the CLI remembers your Dev Hub credentials. The success message should look like this: 

    Success message of authorizing a developer hub

To authenticate Dev Hub is a precondition for creating a scratch org, which is an ephemeral environment for developing on the Salesforce Platform. We create one in the next step.

Create a Scratch Org

  1. In Visual Studio Code, press Command + Shift + P on macOS or Ctrl + Shift + P on Windows or Linux.
  2. Type sfdx.
  3. Select SFDX: Create a Default Scratch Org....
  4. Press Enter to accept the default project-scratch-def.json.
  5. Press Enter to accept the default trailhead scratch org alias.
  6. Press Enter to accept the default 7 days scratch org duration.

Be patient, creating a scratch org can take a minute. The success message should look like this in the output panel of VS Code:

17:18:11.779 sfdx force:org:create -f

config\project-scratch-def.json --setalias trailhead 

--durationdays 7 --setdefaultusername --json --loglevel fatal ended with exit code 0

Now you're all set to develop your first Lightning web component. If you want to learn more about Salesforce DX check out App Development with Salesforce DX.

Create a Lightning Web Component

Creating a Lightning web component is a straightforward process. And Salesforce CLI already created a project structure that helps make getting started even easier.

The folder structure looks like this:

File explorer view of Salesforce DX project within Visual Studio Code, showing subdirectories including .sfdx, .vscode, config, and force-app.

The project we created has a special folder, force-app/main/default. This folder, called a package directory, contains all the metadata of your current Salesforce DX project. Because Lightning web components are also metadata, they are stored in a subfolder named lwc. In the next step, we add a Lightning web component to this folder.

Note

There are also two files, .eslintrc and jsconfig.json, in the lwc folder. We explore them later in this project.

We can use Visual Studio Code to create a Lightning web component, just as we did to create the Salesforce DX project. (You could use Salesforce CLI directly, but we'll use it through the embedded terminal in Visual Studio Code now.)

  1. Open Visual Studio Code.
  2. Press Command + Shift + P on macOS or Ctrl + Shift + P on Windows or Linux.
  3. Type focus terminal and select Terminal: Focus Terminal.
    The Terminal tab (next to Output) is selected.
  4. In the Terminal tab, enter sf lightning generate component -n myFirstWebComponent -d force-app/main/default/lwc --type lwc, and press Enter.

This creates the needed files for your first Lightning web component.

Metadata directory structure with expanded Lightning web component folder

These are the parameters you used in the command.

  • -n defines the name of the Lightning web component folder and its files.
  • -d defines the target directory where the Lightning web component should be created. The target directory must be named lwc.
  • --type specifies that you want to create a Lightning web component.
Note

As you experienced, it's easy to use Salesforce CLI in your development process. If you want to use Visual Studio Code for this instead, right-click the lwc folder or open the Command Palette in Visual Studio Code. Both provide the option SFDX: Create Lightning Web Component, which then invokes Salesforce CLI.

Adding Code and Metadata to Your First Lightning Web Component

Let's take a look now at the files that make up a Lightning web component. For that you're going to copy and paste some HTML, JavaScript, and XML that we've prepared for you. We start with the myFirstWebComponent.js-meta.xml file.

  1. Open the myFirstWebComponent folder, which you just created in the lwc subfolder
  2. Click myFirstWebComponent.js-meta.xml.
  3. Replace the contents of the XML file with this XML markup:

    <?xml version="1.0" encoding="UTF-8"?>
    <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
       <apiVersion>51.0</apiVersion>
       <isExposed>true</isExposed>
       <targets>
           <target>lightning__AppPage</target>
           <target>lightning__RecordPage</target>
           <target>lightning__HomePage</target>
       </targets>
    </LightningComponentBundle>
  4. Press CMD + S on macOS, or CTRL + S on Windows or Linux, to save the file.

The file that you just updated is the metadata definition file. It contains several configuration elements that control, for example, where you can add it to the Salesforce user interface using Lightning App Builder (targets). You can read more about the metadata configuration options in the documentation.

Next we update the JavaScript file of your Lightning web component.

Note

The JavaScript code and HTML markup that you're about to copy and paste have some errors built in. So don't worry about the red squiggly lines that you see. Later in this project you resolve the errors using the capabilities of Visual Studio Code combined with the Salesforce Lightning Web Components extension.

  1. In Visual Studio Code click myFirstWebComponent.js.
  2. Replace the entire contents of the file with this code:

    import { LightningElement } from 'lwc';
    export default class MyFirstWebComponent extends LightningElement {
        @track
        contacts = [
            {
                Id: 1,
                Name: 'Amy Taylor',
                Title: 'VP of Engineering',
            },
            {
                Id: 2,
                Name: 'Michael Jones',
                Title: 'VP of Sales',
            },
            {
                Id: 3,
                Name: 'Jennifer Wu',
                Title: 'CEO',
            },
        ];
    }
  3. Press CMD + S on macOS, or CTRL + S on Windows or Linux, to save the file.

After you save the file you'll immediately notice a few things.

  • The annotated word @track is underlined with a red squiggly line.
  • The JavaScript file color in the explorer changed to red.

    Open JavaScript file with errors highlighted
Note

Depending on your setup, you may see only one error.

Both are indicators that something in the JavaScript code is not correct. As a good developer, you would typically fix it right away.

But for now you can ignore the issues. Instead, add HTML markup to the web components template file.

  1. In Visual Studio Code click myFirstWebComponent.html.
  2. Insert this markup within the existing <template></template> tags:

    <lightning-card title="ContactInformation" icon-name="custom:custom14">
       <div class="slds-m-around_medium">
          <template for:each={} for:item="contact">
             <div>
                {contact.Name}, {contact.Title}
             </div>
          </template>
       </div>
    </lightning-card>
  3. Press CMD + S on macOS, or CTRL + S on Windows or Linux, to save the file.

Again, you see an indication that something in the HTML markup isn't as it should be.

HTML template file open with error on line 4 highlighted

Let's also ignore this (for now).

Usually the next step would be to deploy your project to your org. But the code is full of errors, and the deployment would fail. You may or may not encounter failed deployments in real life. It's important that you pay attention to any errors that are shown in the IDE and fix them right away.

In the next and final step, we fix our code.

Keep learning for
free!
Sign up for an account to continue.
What’s in it for you?
  • Get personalized recommendations for your career goals
  • Practice your skills with hands-on challenges and quizzes
  • Track and share your progress with employers
  • Connect to mentorship and career opportunities