Use Lightning Web Components in Visualforce Pages

With Summer ’19 release, salesforce has introduced the use of lwc in visualforce pages. It will be used in same way like any aura components before.

Before starts, please sign up for pre-release developer edition.

Steps to add the Lightning web component in the visualforce page.

  1. Add the Lightning Web Components for Visualforce JavaScript library to your Visualforce page using the <apex:includeLightning/> component.

<apex:page>
  <apex:includeLightning />

……

</apex:page>

2. Create and reference a standalone Aura app that declares your component dependencies.

<aura:application extends=”ltng:outApp” access=”GLOBAL”>
<aura:dependency resource=”c:demolwcforLighntingout” />
<aura:dependency resource=”markup://force:*” type=”EVENT”/>
</aura:application> 

Below is the lwc definition

<template>
<lightning-card title=”Hello” icon-name=”custom:custom14″>
<div class=”slds-m-around_medium”>
Hello, {greeting}!
</div>
</lightning-card>
</template>

import { LightningElement,api } from ‘lwc’;

export default class DemolwcforLighntingout extends LightningElement
{
@api greeting ;
}

3. Write a JavaScript function that creates the component on the page using $Lightning.createComponent().

<apex:page>
  <apex:includeLightning />
  <div id=”container”>
</div>

<script>
$Lightning.use(“c:lwcContainerApp”, function()
{
$Lightning.createComponent(
“c:demolwcforLighntingout”,
{‘greeting’:’Somnath’},
“container”,
function(cmp)
{
console.log(‘component created’);
});
});
</script>
</apex:page>


Note: You can pass arguments to the lightning web components. In lwc, that property must be publicly accessible. So marking it with @api.

Use namespace:camelCaseComponentName naming convention to reference the Lightning web component.

Resources: https://releasenotes.docs.salesforce.com/en-us/summer19/release-notes/rn_lwc_vf.htm

Lightning Web Components

Salesforce has introduced a new programming model for lightning components called ‘Lightning Web Components’. It leverages web standards breakthroughs, can coexist and interoperate with the Aura programming model, and delivers unparalleled performance. But to use that we need sfdx.

This blog post will show you how to create a very basic LWC and to understand the core concept of it.

We need pre-release developer edition to work on this exercise. Once you are singed in, please enable the dev hub.

VS code can be used to easily achieve this. We can use all the pre build commands to easily create lightning web components.

To work with the lighting web component, you need to install‘Lightning Web Component’ extension in vs code.

Once this is installed, you can follow the below step tocreate a Lightning web components.

  1. Create a sfdx project.
  • Authorize a dev-hub (Use the same accountthat you created now in pre-release edition)
  • Create a default scratch org using default using default projet-scratch-def.json

  • sfdx force:org:create -f config\project-scratch-def.json–setalias Mylwc –durationdays 7 –setdefaultusername
  • Create a apex class which will be controller ofthe lwc.

Add the controller method

public with sharing class LoadContact {

    public LoadContact() {

    }

    @AuraEnabled(cacheable=true)

    public static List<Contact> getContactList(){

        return [Select Id,FirstName,LastName,Email from Contact];

    }

}


Here comes the main attraction – Lightning Web Components

Upon creation of LWC, it will create a three files by default.

  1. LoadContact.html
  2. LoadContact.js
  3. LoadContact.js-meta.xml
  1. LoadContact.html

<template>

    <lightning-card title=”LoadContact” icon-name=”custom:custom63″>

        <div class=”slds-m-around_medium”>

            <p class=”slds-m-bottom_small”>

                <lightning-button label=”Load Contacts” onclick={handleLoad}></lightning-button>

            </p>

            <template if:true={contacts}>

                <template for:each={contacts} for:item=”contact”>

                    <p key={contact.Id}>{contact.Name}</p>

                </template>

            </template>

        </div>

    </lightning-card>

</template>

Template: The template element is used to declare fragments of HTML that can be cloned and inserted in the document by script.

  • LoadContact.js

import { LightningElement, track } from ‘lwc’;

import getContactList from ‘@salesforce/apex/LoadContact.getContactList’;

export default class LoadContact extends LightningElement {

    @track contacts;

    @track error;

    handleLoad() {

        getContactList()

            .then(result => {

                this.contacts = result;

            })

            .catch(error => {

                this.error = error;

            });

    }

}

LightningElement: Base class for the Lightning Web Component JavaScript class

The following piece of JS code determine which Server side apex controller to trigger:

import getContactList from ‘@salesforce/apex/LoadContact.getContactList’;

track: Decorator to mark private reactive properties

  • LoadContact.js-meta.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<LightningComponentBundle xmlns=”http://soap.sforce.com/2006/04/metadata” fqn=”LoadContact”>

    <apiVersion>45.0</apiVersion>

    <isExposed>false</isExposed>

    <targets>

        <target>lightning__AppPage</target>

        <target>lightning__RecordPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>

This xml file determine where these lwc can be used.

isExposed flag determines if you are exposing component to push to your scratch org. By default the value is false. Remember to make it true before you push.

Run the below command to check the difference between your local and scratch org.

Below is the result:

Push the changes to scratch org.

Changes will be pushed from your local to your scratch org.

Now this custom Lightning Web Component is available to you use in lightning app builder pages.

If you click on Load contact button it should retrieve all the available contacts from your org. It makes server side apex call to fetch the same.

In this Lightning web component Series, I will go in much deeper concept in my next posts. I will cover what is the differences between LWC and aura framework and what is performance improvement factors of this new frame work.

Please add/post your valuable comments.

Happy learning !!!!