Use Lightning Web Components in Visualforce Pages

If there exists a Visualforce page in your project on which the team has spent say 6 months, is it suggested that we convert that to Lightning Web Components?

If there exists a Visualforce page in your project on which the team has spent say 6 months, is it suggested that we convert that to Lightning Web Components?

Well, if you want to go ahead and convert it nothing like it. But considering the time and resources, it's suggested that we don't touch the Visualforce page at all and use Lightning Web Components for the new enhancements.

The reason I propose this solution is Lightning is so flexible that we can embed the LWC component into a Visualforce page and use it without any hassle.

However, it's not that straightforward. We cannot embed an LWC into a Visualforce page directly, we need to break it down into 2 steps.

  1. Embed the LWC into a Lightning App
  2. In turn embed the Aura Component into a Visualforce page.
How to embed Lightning Web Component into an Aura Component

Here is a sample snippet that shows it all.

<template>
  <p>Hello World</p>

  <lightning-button label="subs" onclick={handleClick}></lightning-button>

</template>
exploreHelloWorld.html
import { LightningElement, wire } from "lwc";

export default class ExploreHelloWorld extends LightningElement {

  handleClick() {
    console.log('What are you snooping at 👀');
  }
  
}
exploreHelloWorld.js

Here am trying to embed the LWC Component into the Lightning App.

<aura:application access="GLOBAL" extends="ltng:outApp"> 
    <aura:dependency resource="c:exploreHelloWorld"/>
</aura:application>
exploreHelloWorldApp.app

Here am trying to embed the Lightning App into the Visualforce page.

<apex:page lightningStylesheets="true">
        <!-- This is used to include the JS files that makes embedding a Lightning App in  VF page possible -->
    <apex:includeLightning />
    
        <!-- This is where the component gets embeded -->
    <div id="lightning" />

    <script>
                //1. Specify the Lightning App
        $Lightning.use("c:testingLWCinVF", function () {
                        //2. Specify the Aura Component that has LWC in it
            $Lightning.createComponent("c:exploreHelloWorld",
                {},
                "lightning",
                function (cmp) {
                    console.log("button was created");
                    // do some stuff
                }
            );
        });
    </script>
</apex:page>
exploreHelloWorld.vfp

Bit of a workaround sort of a thing but it works super smooth.

Not sure if Salesforce has something in mind in terms of giving us the flexibility to directly embed an LWC into a Visualforce page. But as of this suffices our need.