Understanding files in Lightning Web Components

Getting started with Lightning Web Components

Understanding files in Lightning Web Components

Sine we looked at creating a project using VSCode and Salesforce DX in the previous post lets dive in and understand the syntaxes of the files.

We can create a Lightning Web Component either by choosing the appropriate option in the file explorer(as shown below).

Creating Lightning Web Component using file explorer
Creating Lightning Web Component using file explorer

or we can also create a Web Component using the command palette(as shown below)

Creating Lightning Web Component using Command Palette
Creating Lightning Web Component using Command Palette

We will typically get access to three files when we create a Web Component, first, a template or html file then a js file and then a xml file.

Let’s start off with the template/html file

<template>
    //add ui elements here
</template>

In a Visualforce page just like how we are supposed to put all the markup between the <apex:page></apex:page> tags we need to put all the UI elements related markup between the <template></template> tags.

Then, we have a js file and if you look at the syntax of the file it looks something like this.

import { LightningElement } from 'lwc';

export default class HelloWord extends LightningElement {
	//do something here
}

There are three steps that are involved here

Step1 - Import the dependencies, and in this case we are trying to import LightningElement from the package lwc.

Step2 - With in the class file, have all the business logic that you wish to have.

Step3 - Finally export the class(this class acts as a module now) so that we can import it in other web components.

Last, we get access to a xml file and it looks something like this

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

We are trying to specify the api version here, then we are trying to expose the file so that we can access the component in the Lightning App Builder. Finally we are trying to mention that targets where this component can be used, as far the above snippet is concerned this component can be used in AppPage, RecordPage or HomePage.

Not only this we can also have a css file and svg file with respective to this component. However, for one web component we can only have one svg file.