Sunday, May 24, 2020

How to Use Lightning Web Components(LWC) in Visualforce Pages

Hello All,
Today we are going to understadn ,howe we can use/Access Lightning Web component in to Visualforce  page.we need to know because some of customer using Visualforce as per thire requirement .Sometimes there is a requirement to use lightning component in visualforce page.
Lightning web Components for Visualforce is based on Lightning Out, a powerful and flexible feature that lets you embed Lightning components into almost any web page. 
basic example of the lightning component and then display lightning component in the visualforce page.

helloLWCComponentForVF.html
1
2
3
4
5
6
7
<template>
    <lightning-card title="Use LWC in Visualforce" icon-name="custom:custom19">
        <div class="slds-m-around_medium">
            This is LWC Component and we will use it in to visualforce page
        </div>
    </lightning-card>
</template>
helloLWCComponentForVF.js
1
2
import { LightningElement } from 'lwc';
export default class HelloComponentForVFLWC extends LightningElement {}
helloLWCComponentForVFApp.app
Here important point is that ltng:outApp needs to be extended in app.
ltng:outApp adds SLDS resources to the page to allow our Lightning components to be styled with the Salesforce Lightning Design System. If we don’t want SLDS resources added to the page, we need to extend from ltng:outAppUnstyled instead.
1
2
3
<aura:application extends="ltng:outApp" access="GLOBAL">
    <aura:dependency resource="helloLWCComponentForVF" />
</aura:application>
HelloLWCMyVF.page
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<apex:page showHeader="false" sidebar="false">
    <apex:includeLightning />   
    <div id="LightningComponentid" />   
    <script>
    $Lightning.use("c:helloLWCComponentForVFApp", function() {
        $Lightning.createComponent("c:helloLWCComponentForVF",
          {
          },
          "LightningComponentid",
          function(cmp) {
             console.log('We have added LWC Componenet in VF page');
          });
    });
    </script>
</apex:page>

VF page OutPut:-
 This is LWC Component and we will use it in to visualforce page
In the above Visualforce page, apex:includeLightning tag imports necessary dependencies and scripts to enable Visualforce to act as Lightning component container.
We can use $Lightning.use() method in JavaScript to refer to Lightning Application which extends ltng:outApp.
We can use $Lightning.createComponent create Lightning Component dynamically.
We can call $Lightning.use() multiple times on a page, but all calls must reference the same Lightning dependency app.
we can get more detail over the salesforce offical document here .