Setup Dev Environment to create first Lightning Web Component (LWC)

INTRODUCTORY SERIES

Anatomy of Lightning Web Component

In the introductory blog post, we learnt about the ‘What-Why-How’ of a new paradigm of UI development in Salesforce called as Lightning Web Component (LWC) framework. It is next in the evolutionary phase after the Aura framework and Salesforce has made big bets on it by going open source. In this post, we are going…

Lightning Web Components – Introduction (In Pictures)

This blog is primarily intended to serve as a refresher and a quick primer to know and then speak about LWC to anyone (customers, partners, fellow developers and in community). I have always tried to conceive complex ideas and concepts with visualizations. It helps with the retention and gives you talking points to speak if…

We learnt the basics of lightning web components in an introductory two part series – Introduction to LWC and Anatomy of a web component. But before we start brewing some kickass web components, we need to prepare our kitchen and gather the apt utensils! In this blogpost, we are going to setup the development environment needed to create and deploy lightning web components for our Salesforce orgs.

However you might be wondering – “I never needed to setup anything while creating VF pages or even Aura components. I could simply create them in Developer Console. Why do I need it now ?”

Quick answer is – Because you cannot create lightning web components in Developer Console.

You cannot create lightning web components in Developer Console.

But this is also tied to the paradigm shift that has recently occurred in the Salesforce development lifecycle, weighing more on Source driven development against the yesteryear’s Org based development. This new methodology also called as ‘Salesforce DX’ consists of new tools that streamline the entire development life cycle. In this blogpost, we are going to look at the bare minimum tooling that is needed to ship your first lightning web component. So let’s start

Tools needed for development – Salesforce CLI, VS code and Org (scratch/Non scratch org)

1. Salesforce Command Line Interface

Salesforce CLI is a command-line-interface which can help you (and VS code!) talk with the Salesforce org in form of ?

YES ! “Commands” (What else ?)

It is a powerful tool which can help you create LWCs, Apex classes, deploying and retrieving the metadata to/from Salesforce, execute unit tests, create and install packages etc. As you would have guessed, there is not much you can do without Salesforce CLI. Download the CLI as per your OS with help from below links

OSInstallation Link
macOShttps://sfdc.co/sfdx_cli_osx
Windows(32 Bit)https://sfdc.co/sfdx_cli_win
Windows(64 Bit)https://sfdc.co/sfdx_cli_win64
Debian/Ubuntu(x64)https://sfdc.co/sfdx_cli_linux
Debian/Ubuntu(x86)https://sfdc.co/sfdx_cli_linux_x86

Once the CLI installer is downloaded, click on it and the installation commences. After the installation is completed you might need to set the path in your environment variables. To verify if CLI is ready to go just type the below command in terminal (macOS) or command-prompt (windows)

sfdx --version

You will see the CLI spitting out something like below

anandgupta@Anands-MBP Documents % sfdx --version
sfdx-cli/7.74.1-32db2396ed darwin-x64 node-v12.18.3

We are done with the first step of setting up our kitchen and not far from rolling hot components on the table! Let’s not stop. Next we will be setting up our IDE.

2. Visual Studio Code – Install Salesforce Extension packs, Setup linting

But wait! What’s an IDE ?

IDE stands for Integrated Development Environment. It is basically a Text Editor but for Coding and having superpowers like – Code completion, debugger, automation tools etc. It is your saucepan to write recipes. There are many IDEs which can be used to write code, but for Salesforce the official recommendation is to use Visual Studio Code.

So let’s start by Downloading and Installing Visual Studio Code

  1. Download and install the latest version of the Visual Studio Code as per the OS
  2. Launch Visual Studio Code

Because VS Code is a generic code editor which is also used for development of many other programming languages like Java, python etc, it needs a special Salesforce flavouring. That is brought using what are called as – Extension packs.

But there is not much to think here as there is only one extension pack which you need to download and it takes care of everything (One ring to rule em all!). Follow along

  1. Open Visual Code Editor
  2. Click on the ‘Extension Icon’ from the left pane
  3. Search for ‘Salesforce Extension Pack’ in the search bar (You will see something like below)

4. Click on the Salesforce Extension Pack and you will see the documentation of the extension with a green ‘Install’ button. Clicking it will start the installation. Once the installation is complete, you can start using it straightaway without closing or reloading the editor.

This extension pack also installs some additional needed packs for Salesforce development along with it. So there is no need to install these packs individually.

Things are looking great. But we need to worry about the cleanliness as well. We have a tool just for that purpose and it is called as ‘Linter’.

Linting finds errors in your code as you are typing it. Sweat more while your coding so that you can bleed less when compiling ! It consists of set of rules that run on your code based on defined patterns and practices. Salesforce Extension Pack by default installs ‘ESLint’ on your VSCode such that it runs everytime you work on a Lightning Web Component.

That completes our kitchen work!

3. Request a Salesforce Developer Edition Org and enable MyDomain

If you already have a Salesforce Developer Org, you can skip this step. To request one, sign up for a developer edition org using the below link below

Developer Edition Sign-up Form

Lightning web components can be created in both scratch and non scratch orgs. For simplicity of the topic, we are going to consider non-scratch orgs for discussion. Before you can start using Lightning web components, myDomain should be enabled in for any org.

Follow the steps here to enable myDomain for any org.

4. Create a project to start the development

A project holds the necessary structure of the Salesforce code base in the form of metadata files grouped in relevant folders stored locally. So let’s start to create a project which will house one of our metadata (lightning web component).

  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. Choose a name (Leonardo ?), and press Enter.
  4. Choose a directory on your local machine where the project will be stored. Click Create Project.

Done! We next need to authorize our Salesforce Org and connect it to VS Code.

5. Authorize Development Environment in VS Code (Non Scratch Org methodology)

  1. Run SFDX : Authorize an Org command from the Command Palette in VS Code and select a login URL.
  2. Provide an alias(short name) for this org.
  3. Next a browser window will open –> Click on ‘Allow Access’ –> Return back to VS Code.

We are now ready to create our first Lightning Web Component

6. Create your first lightning web component

Just like how we used the Command Palette of VS code to create a project and authorize an org, we can use it again to create a lightning web component quickly

  1. Open Visual Studio Code.
  2. Press Command + Shift + P on macOS or Ctrl + Shift + P on Windows or Linux, then type Create and use the suggested ‘ SFDX : Create Lightning Web Component’
  3. Enter a suitable name.

This will create the necessary files (remember the anatomy of lwc) in the ‘lwc’ folder in your project. Fistbump ? (You have just created a lightning web component and it is ready to be deployed)

With this – We have now setup the complete tooling and path needed to develop Salesforce components (Apex Classes, VF pages, Aura components, Lightning Web Components, Apex Triggers etc) in our local system and deploy them to a Salesforce org.

Anatomy of Lightning Web Component

In the introductory blog post, we learnt about the ‘What-Why-How’ of a new paradigm of UI development in Salesforce called as Lightning Web Component (LWC) framework. It is next in the evolutionary phase after the Aura framework and Salesforce has made big bets on it by going open source.

In this post, we are going to go a level further and explore the various building blocks that make up a lightning web component. So let’s get started

Every Lightning web component is made up of 3 basic files –

  • A HTML file – This file defines the structure of the component.
  • A Javascript file – This file establishes the behaviour of the component.
  • A metadata file – This is a configuration file which houses the metadata information.

Now lets look them in detail

HTML

Every Lightning component must have a HTML file with a root tag <template>. The naming convention of the HTML file is as follows

<component>.html

For eg : If you decide to name your lightning web component as ‘myComponent’ then the html file will look like – myComponent.html

The actual markup of the HTML goes inside the <template> tags as below

<!-- myComponent.html -->
<template>
    <!-- In goes the HTML markup of your supercalifragilisticexpialidocious component!!!! -->
</template>

On the browser, when the component is rendered, the <template> tag is replaced with actual name of the component. So the above component will be rendered as <c-my-component>(kebab case – Delicious !).

Now a very common scenario during UI development is to ‘Show/Hide’ certain parts of the component (markup) based on condition. This can be easily done using what is called as ‘directive’ in modern web standard parlance. One of the very commonly used directive is ‘if:true|false’ directive.

We are going to look at this in detail in the upcoming posts, but I just wanted to give you a sneak peek of what it looks like in HTML

The below component is composed of 2 templates. The second template is composed inside the parent template. Pay attention to the if:true={shouldHelloBeVisible} directive used in the second template which is used to dynamically show/hide the ‘Hello!’ message.

<!-- myComponent.html -->
<template>
    <lightning-card title="ConditionalRendering" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
            <lightning-input type="checkbox" label="Say Hello" onchange={handleChange}></lightning-input>
            <template if:true={shouldHelloBeVisible}>
                <div class="slds-m-vertical_medium">
                    Hello!
                </div>
            </template>
        </div>
    </lightning-card>
</template>

We are going to look at how to set the ‘shouldHelloBeVisible’ property in the next section – Javascript

Javascript

Every lightning component must have have a Javascript file. It defines the HTML element. The naming convention of a Javascript file is as follows

<Component>.js

So if we have a component ‘myComponent’ then the javascript file name will be myComponent.js

Every lwc UI component must include a Javascript file with the below code

import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement {
// Your paracetamoxyfrusebendroneomycin code goes here!!
}

There is lot going on in those few lines of code. Let me break it for you. So

  1. import { LightningElement } from ‘lwc’ – In this line we are importing ‘LightningElement’ from the ‘lwc’ module. ‘lwc’ is a standard core module of Lightning Web Component framework. ‘LightningElement’ is the custom wrapper of the standard HTML element. Think of it like this – Before you can create an fusion ice-cream dessert, you are first bringing a vanilla (LightningElement) scoop from your fridge (lwc module) on your plate

2. export default class MyComponent extends LightningElement – Once you have the vanilla ice-cream on your plate, you are going to extend it with more flavours to create that perfect combination. So in this line we extend the base ‘LightningElement’ and give a name to our class (more about the class name in a second). With ‘export default’ keyword, we are also exporting this class so that other classes could eventually import it and then reuse/repurpose it for own use.

Javascript class names must have a Pascal naming convention. For eg : If the file name is ‘myComponent.js’ then the class name will be ‘MyComponent’ (first letter of each word is capitalized)

Javascript files in Lightning Web Component framework usually contains –

  • The component’s public API via public properties and methods annotated with @api.
  • Private properties
  • Event handlers

Let’s look at the Javascript file for our myComponent (described earlier) which sets the ‘shouldHelloBeVisible’ property to conditionally render the template

// myComponent.js
import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
    shouldHelloBeVisible = false;

    handleChange(event) {
        this.shouldHelloBeVisible = event.target.checked;
    }
}

Pretty easy ! Isn’t it ? For a start – Yes !

Now our HTML and Javascript file are ready for action. But we need one last file to glue it all together – The metadata configuration file.

Configuration

Every component must have have configuration file. It defines the metadata values of the component and also the design configuration needed for Lightning App Builder.

The naming convention of the Configuration file is as below

<component>.js-meta.xml

So for a ‘myComponent’ the configuration file will be named as myComponent.js-meta.xml

If you don’t include a configuration file while defining the component and then try to push it in a Salesforce org, you will get the below error

Cannot find Lightning Component Bundle <component_name>

Now let’s look at the configuration file for our component created for conditional rendering

<?xml version="1.0" encoding="UTF-8" ?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Here the target tags define where all in Lightning Experience we can use this component. So the above configuration file enables our component to be dragged on the App Page, Record Page as well as Home Page.

If isExposed is false, the component is not exposed to Lightning App Builder or Experience Builder.

But the above files – HTML, Javascript and Configuration are only the must haves? Yes ! You can optionally also define below files for your lightning web component

  • An optional CSS File – To style a component, create a style sheet in the component bundle with the same name as the component. If the component is called myComponent, the style sheet is myComponent.css. The style sheet is applied automatically.
  • An optional SVG File – To include an SVG resource as a custom icon for your component, add it to your component’s folder. It must be named <component>.svg. If the component is called myComponent, the svg is myComponent.svg. You can only have one SVG per folder.
  • Other Javascript Files – Use these JavaScript files to share code.
  • Test Files – You can test your lightning web components using Jest framework. Test files must have names that end in “.js”, and the recommendation is to use “.test.js”.

Finally all of these files have to be bundled together under a component folder like below

To recap – Every lightning web component is basically structured around – A HTML file, A Javascript file and a Configuration File. We will continue to explore some advance topics on Lightning Web Component framework in coming posts. Till then – Stay safe and happy learning !