SlideShare une entreprise Scribd logo
1  sur  32
Télécharger pour lire hors ligne
Migrez vos composants Lightning vers
Lightning Web Components
martinlezer@gmail.com, @martinlezer
Martin LEZER, Expert technique Salesforce chez Business&Decision
Martin LEZER
Expert technique Salesforce
chez Business&Decision
This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any
of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking
statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or
service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for
future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts
or use of our services.
The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our
service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth,
interruptions or delays in our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible
mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our
employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com
products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of
salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most
recent fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor Information
section of our Web site.
Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be
delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available.
Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
Statement under the Private Securities Litigation Reform Act of 1995
Forward-Looking Statement
“You can now develop Lightning components in two programming
models: the original model—Aura Components, and the new model—
Lightning Web Components.
Just when you’ve mastered developing Aura components, we’ve
come up with Lightning web components! Why, oh why, you ask?
Well, we created the Lightning Web Components model to align with
web standards that didn’t exist several years ago when we built the
original Aura model.”
Un nouveau modèle de programmation
Productivité améliorée
Utilisation des langages modernes du Web: ES6+,
Elements personnalisés, et Shadow DOM
Conçu pour la performance
Plus de code exécuté par le navigateur au lieu
d’abstractions JavaScript pour une expérience plus
rapide
Compatible et facile à utiliser
Exécuté simultanément avec des composants
Lightning existants
Un nouveau modèle de programmation construit sur les standards du Web
Introduction - Lightning Web Components
LWC vs Aura
Standards du Web
LWC vs Aura
LWC vs Aura
Fichier HTML Optionnel
• nommé suivant la convention <component>.html
• avec comme balise racine <template>
• équivalent du fichier de composant Aura
Fichier JavaScript
• nommé suivant la convention <component>.js
• inclut une classe de composant standard
• réunit les controller et helper JavaScript Aura
Fichier de configuration
• nommé suivant la convention <component>.js-meta.xml
• permet de spécifier les pages sur lesquelles le composant peut être
ajouté en précisant le type de page et le type d’objet
LWC
Aura
Structure des fichiers
LWC
Structure de la classe du composant JavaScript
Structure des fichiers
LWC vs Aura
Aura
Structure du controller JavaScript
import { LightningElement } from "lwc";
export default class MyComponent extends LightningElement {
// your code here
}
({
myFunction: function(component, event, helper) {
}
});
• Equivalent aux attributs sur Aura
• Variables JavaScript accessibles par le template HTML à certaines conditions
• Différents types de propriétés:
• privée: variable seulement utilisée dans le code JavaScript
• réactives: si la valeur d’une variable change, elle est mise à jour dans le template
• publique: accessible par un composant parent
• tracked: variable privée
Propriétés
LWC vs Aura
Propriétés
LWC vs Aura
LWC
Classe de composant JavaScript
HTML
Aura
HTML
Controller JavaScript
import { LightningElement, api, track } from 'lwc';
export default class TodoItem extends LightningElement {
@api itemTitle = ''; // public
itemId = ''; // private
@track state = { x: 100, y: 100 }; //internal & reactive
}
<template>
<div class="view">
<label>{itemTitle}</label>
</div>
</template>
<aura:component>
<aura:attribute name="itemTitle" type="String" />
<aura:attribute name="itemId" type="String" />
<aura:attribute name="state" type="Object" />
<aura:handler name="init" action="{!c.doInit}"
value="{!this}" />
<div class="view">
<label>{!v.itemTitle}</label>
</div>
</aura:component>
({
doInit: function(component, event, helper) {
component.set("v.state", {x: 100, y: 100});
}
});
LWC
Rendu conditionnel
Expressions HTML
LWC vs Aura
Aura
Rendu conditionnel
<template if:true={areDetailsVisible}>
<div class="slds-m-vertical_medium">
These are the details !
</div>
</template>
<aura:if isTrue="{!v.areDetailsVisible}">
<div class="slds-m-vertical_medium">
These are the details !
</div>
</aura:if>
LWC
Iterations
Expressions HTML
LWC vs Aura
Aura
Iterations
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>
{contact.Name}, {contact.Title}
</li>
</template>
<aura:iteration items="{!v.contacts}"
itemVar="contact">
<li key={!contact.Id}>
{!contact.Name}, {!contact.Title}
</li>
</aura:iteration>
Expressions complexes
LWC vs Aura
LWC
HTML
JavaScript
Aura
HTML
<template if:false={isFirstPage}>
<lightning-button-icon icon-name="utility:chevronleft"
onclick={previousHandler}>
</lightning-button-icon>
</template>
@api pageNumber;
get isFirstPage() {
return this.pageNumber === 1;
}
<aura:if isTrue="{!v.page > 1}">
<lightning:buttonIcon
iconName="utility:left"
variant="border"
onclick="{!c.previousPage}"/>
</aura:if>
• Les expressions Aura avec opérations logiques sont migrées vers du code JavaScript
• Utilisation de getters
Initialisation
LWC vs Aura
LWC
JavaScript
Aura
HTML
JavaScript
import { LightningElement } from 'lwc';
export default class MySampleInit extends LightningElement{
connectedCallback() {
// initialize component
}
}
<aura:handler name="init" value="{!this}"
action="{!c.doInit}"/>
({
doInit: function(cmp) {
// initialize component
}
})
Evénements personnalisés
LWC vs Aura
LWC
JavaScript
Aura
HTML – Event
HTML – Composant
JavaScript – Composant// Creates the event with the contact ID data.
const selectedEvent = new CustomEvent(
'selected’,
{ detail: this.contact.Id }
);
// Dispatches the event.
this.dispatchEvent(selectedEvent);
<aura:event type="COMPONENT"
description="Item selected">
<aura:attribute name="contactId" type="Id" />
</aura:event>
• Utilisation des standards du web avec le
constructeur CustomEvent()
• Déclenchement de l’événement avec la
méthode dispatchEvent()
<aura:registerEvent name="itemSelected"
type="c:itemSelected"/>
var selectedEvent=cmp.getEvent("itemSelected");
selectedEvent.setParams({
contactId: cmp.get("v.contact").Id
});
selectedEvent.fire();
Evénements personnalisés
LWC vs Aura
LWC
HTML
Aura
HTML
<c-contact-list-item key={contact.Id}
contact={contact}
onselected={contactSelected}>
</c-contact-list-item>
<c:contactListItem contact="{!v.contact}"
itemSelected="{!c.contactSelected}">
</c:contactListItem>
• L’évenement est capté par le parent en ajoutant le préfixe « on » au nom personnalisé
définit précédemment
Fonctionnalités spécifiques à LWC
Wire Service – Manipulation des données
Fonctionnalités spécifiques à LWC
• Surcouche du Lightning Data Service déjà présent avec les composants Lightning
• Permet de lire ou créer un enregistrement sans appel Apex, seulement du JavaScript
• Appelable grâce à l’annotation @wire
• Les références vers les objets et champs utilisés doivent être importées afin de:
• empêcher la suppression de l’objet ou du champ
• vérifier à l’exécution que les références existent
• vérifier l’inclusion des champs et objets utilisés dans le change set
• L’import des références se fait sous la forme suivante:
import OBJECT_NAME from '@salesforce/schema/object';
import FIELD_NAME from '@salesforce/schema/object.field';
Wire Service – Lecture d’un enregistrement
Fonctionnalités spécifiques à LWC
LWC
HTML
<template>
<lightning-card title="My Contact Record"
icon-name="standard:contact">
<template if:true={contact.data}>
<div class="slds-m-around_medium">
<p>{name}</p>
<p>
<lightning-formatted-email
value={email}>
</lightning-formatted-email></p>
</div>
</template>
</lightning-card>
</template>
JavaScript
import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Contact.Name';
import EMAIL_FIELD from '@salesforce/schema/Contact.Email';
export default class GetContact extends LightningElement {
@api recordId;
@wire(getRecord, {
recordId: '$recordId',
fields: [NAME_FIELD, EMAIL_FIELD]
})
contact;
get name() {
return this.contact.data.fields.Name.value;
}
get email() {
return this.contact.data.fields.Email.value;
}
}
Appel aux méthodes Apex
Fonctionnalités spécifiques à LWC
• Nécessaire seulement si le besoin n’est pas couvert par le wire service ou les composants
standards tels que le Lightning Record Form ou les Lightning Record View Form et
Lightning Record Edit Form
• Nécessite l’import de la méthode avec la syntaxe suivante
• Comme pour le framework Aura, une méthode Apex se rend disponible à l’appel grâce à
l’annotation @AuraEnabled
• Il est possible de lier une propriété ou méthode JavaScript à l’appel de la méthode Apex
(à condition qu’elle soit définit comme cachable) avec la syntaxe suivante
import apexMethodName from '@salesforce/apex/Namespace.Classname.apexMethodReference';
@wire(apexMethod, { apexMethodParams })
propertyOrFunction;
Fonctionnalités spécifiques à LWC
LWC
Apex
Appel aux méthodes Apex
@AuraEnabled(cacheable=true)
public static List<Contact> findContacts(String searchKey) {
if (String.isBlank(searchKey)) {
return new List<Contact>();
}
String key = '%' + searchKey + '%’;
return [
SELECT Id, Name, Title, Phone, Email
FROM Contact
WHERE Name
LIKE :key
];
}
JavaScript
import { LightningElement, track, wire } from 'lwc';
import findContacts from
'@salesforce/apex/ContactController.findContacts';
export default class ApexMet extends LightningElement {
@track searchKey = '';
@wire(findContacts, { searchKey: '$searchKey' })
contacts;
}
LWC
JavaScript
Appel aux méthodes Apex – Méthode non cachable
Fonctionnalités spécifiques à LWC
import { LightningElement, track } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';
export default class ApexImperativeMethod extends LightningElement {
@track contacts;
@track error;
handleLoad() {
getContactList()
.then(result => {
this.contacts = result;
})
.catch(error => {
this.error = error;
});
}
Utilitaires JavaScript
Fonctionnalités spécifiques à LWC
LWC
JavaScript – Utilitaire
export const fireEvent = (pageRef, eventName, payload) => {
if (events[eventName]) {
const listeners = events[eventName];
listeners.forEach(listener => {
if (samePageRef(pageRef, listener.thisArg.pageRef)) {
try {
listener.callback.call(listener.thisArg, payload);
} catch (error) {
// fail silently
}
}
});
}
};
• Partagez du code JavaScript entre composants grâce aux standards du Web
JavaScript – Appel de l’utilitaire
import { LightningElement, wire, track } from "lwc";
import { CurrentPageReference } from
"lightning/navigation";
import { fireEvent } from "c/pubsub";
export default class UtiUse extends LightningElement {
@wire(CurrentPageReference) pageRef;
filter(event){
fireEvent(this.pageRef,
"filterOpportunities",
event.detail);
}
}
Démo
https://github.com/mlezer/salesforce-world-tour-lwc
Architecture de l’application
Démo
Conclusion
LWC
Résumé
• Plus de JavaScript
-> moins d’Apex
• Standards du Web
-> plus de développeurs compétents
-> meilleures performances
• Meilleure qualité de code
-> moins de répétitions
-> maintenabilité améliorée
Stack Overflow Developer Survey 2019
• Technologies fondamentalement différentes
-> Analyse préalable des composants à migrer
-> Refactorisation du code Apex et JavaScript
• Aura et LWC peuvent cohabiter
-> un composant Aura peut inclure un composant LWC
• Commencer par les composants les plus simples
-> composants enfants
Stratégie de migration
LWC
Trailhead – Gallerie d’exemples
Aller plus loin
sforce.co/LWC
Gallerie d’exemples - Dreamhouse
Aller plus loin
Amélioration des performances
Migrez vos composants Lightning vers Lightning Web Components

Contenu connexe

Similaire à Migrez vos composants Lightning vers Lightning Web Components

Azure Logic Apps - Bonnes pratiques et industrialisation pour un départ lancé
Azure Logic Apps - Bonnes pratiques et industrialisation pour un départ lancéAzure Logic Apps - Bonnes pratiques et industrialisation pour un départ lancé
Azure Logic Apps - Bonnes pratiques et industrialisation pour un départ lancé
Manon PERNIN
 
Integration Summit 16 - Azure Logic App, bonnes pratiques et industrialisatio...
Integration Summit 16 - Azure Logic App, bonnes pratiques et industrialisatio...Integration Summit 16 - Azure Logic App, bonnes pratiques et industrialisatio...
Integration Summit 16 - Azure Logic App, bonnes pratiques et industrialisatio...
Cellenza
 
Le datacenter élastique d'avanade, gestion unifiée du cloud privé et refactur...
Le datacenter élastique d'avanade, gestion unifiée du cloud privé et refactur...Le datacenter élastique d'avanade, gestion unifiée du cloud privé et refactur...
Le datacenter élastique d'avanade, gestion unifiée du cloud privé et refactur...
Microsoft Technet France
 
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Gregory Renard
 
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Gregory Renard
 
WebSphere Portal & Rich Internet Applications
WebSphere Portal & Rich Internet ApplicationsWebSphere Portal & Rich Internet Applications
WebSphere Portal & Rich Internet Applications
Vincent Perrin
 
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Gregory Renard
 

Similaire à Migrez vos composants Lightning vers Lightning Web Components (20)

Azure Logic Apps - Bonnes pratiques et industrialisation pour un départ lancé
Azure Logic Apps - Bonnes pratiques et industrialisation pour un départ lancéAzure Logic Apps - Bonnes pratiques et industrialisation pour un départ lancé
Azure Logic Apps - Bonnes pratiques et industrialisation pour un départ lancé
 
Integration Summit 16 - Azure Logic App, bonnes pratiques et industrialisatio...
Integration Summit 16 - Azure Logic App, bonnes pratiques et industrialisatio...Integration Summit 16 - Azure Logic App, bonnes pratiques et industrialisatio...
Integration Summit 16 - Azure Logic App, bonnes pratiques et industrialisatio...
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Azure devops
Azure devopsAzure devops
Azure devops
 
FlexNet Manager Suite On-Demand
FlexNet Manager Suite On-DemandFlexNet Manager Suite On-Demand
FlexNet Manager Suite On-Demand
 
AWS Paris Summit 2014 - T2 - Déployer des environnements entreprises hybrides
AWS Paris Summit 2014 - T2 - Déployer des environnements entreprises hybridesAWS Paris Summit 2014 - T2 - Déployer des environnements entreprises hybrides
AWS Paris Summit 2014 - T2 - Déployer des environnements entreprises hybrides
 
Le datacenter élastique d'avanade, gestion unifiée du cloud privé et refactur...
Le datacenter élastique d'avanade, gestion unifiée du cloud privé et refactur...Le datacenter élastique d'avanade, gestion unifiée du cloud privé et refactur...
Le datacenter élastique d'avanade, gestion unifiée du cloud privé et refactur...
 
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
 
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
 
Support cours angular
Support cours angularSupport cours angular
Support cours angular
 
WebSphere Portal & Rich Internet Applications
WebSphere Portal & Rich Internet ApplicationsWebSphere Portal & Rich Internet Applications
WebSphere Portal & Rich Internet Applications
 
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
Visual Basic 9.0 – Visual Studio 2008 Quoi De Neuf 2.0
 
AWS Summit Paris - Track 1 - Session 3 - Abordez la migration de vos applicat...
AWS Summit Paris - Track 1 - Session 3 - Abordez la migration de vos applicat...AWS Summit Paris - Track 1 - Session 3 - Abordez la migration de vos applicat...
AWS Summit Paris - Track 1 - Session 3 - Abordez la migration de vos applicat...
 
[DevTestday] Keynote
[DevTestday] Keynote [DevTestday] Keynote
[DevTestday] Keynote
 
Silverlight 4
Silverlight 4Silverlight 4
Silverlight 4
 
Hébergement SaaS ASP - Forum Solutions-as-a-Service du Club Alliances IBM - 2...
Hébergement SaaS ASP - Forum Solutions-as-a-Service du Club Alliances IBM - 2...Hébergement SaaS ASP - Forum Solutions-as-a-Service du Club Alliances IBM - 2...
Hébergement SaaS ASP - Forum Solutions-as-a-Service du Club Alliances IBM - 2...
 
Alphorm.com Formation Angular - Les fondamentaux
Alphorm.com Formation Angular - Les fondamentauxAlphorm.com Formation Angular - Les fondamentaux
Alphorm.com Formation Angular - Les fondamentaux
 
Angular développer des applications .pdf
Angular développer des applications .pdfAngular développer des applications .pdf
Angular développer des applications .pdf
 
Sayeh hiba-karaa-eya-ferjani-maroua-hamzaoui-balkiss-sys-complexes
Sayeh hiba-karaa-eya-ferjani-maroua-hamzaoui-balkiss-sys-complexesSayeh hiba-karaa-eya-ferjani-maroua-hamzaoui-balkiss-sys-complexes
Sayeh hiba-karaa-eya-ferjani-maroua-hamzaoui-balkiss-sys-complexes
 
Boostez vos applications en migrant vos bases vers SQL Server 2012 !
Boostez vos applications en migrant vos bases vers SQL Server 2012 !Boostez vos applications en migrant vos bases vers SQL Server 2012 !
Boostez vos applications en migrant vos bases vers SQL Server 2012 !
 

Migrez vos composants Lightning vers Lightning Web Components

  • 1. Migrez vos composants Lightning vers Lightning Web Components martinlezer@gmail.com, @martinlezer Martin LEZER, Expert technique Salesforce chez Business&Decision
  • 2. Martin LEZER Expert technique Salesforce chez Business&Decision
  • 3. This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section of our Web site. Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements. Statement under the Private Securities Litigation Reform Act of 1995 Forward-Looking Statement
  • 4. “You can now develop Lightning components in two programming models: the original model—Aura Components, and the new model— Lightning Web Components. Just when you’ve mastered developing Aura components, we’ve come up with Lightning web components! Why, oh why, you ask? Well, we created the Lightning Web Components model to align with web standards that didn’t exist several years ago when we built the original Aura model.” Un nouveau modèle de programmation
  • 5. Productivité améliorée Utilisation des langages modernes du Web: ES6+, Elements personnalisés, et Shadow DOM Conçu pour la performance Plus de code exécuté par le navigateur au lieu d’abstractions JavaScript pour une expérience plus rapide Compatible et facile à utiliser Exécuté simultanément avec des composants Lightning existants Un nouveau modèle de programmation construit sur les standards du Web Introduction - Lightning Web Components
  • 8. LWC vs Aura Fichier HTML Optionnel • nommé suivant la convention <component>.html • avec comme balise racine <template> • équivalent du fichier de composant Aura Fichier JavaScript • nommé suivant la convention <component>.js • inclut une classe de composant standard • réunit les controller et helper JavaScript Aura Fichier de configuration • nommé suivant la convention <component>.js-meta.xml • permet de spécifier les pages sur lesquelles le composant peut être ajouté en précisant le type de page et le type d’objet LWC Aura Structure des fichiers
  • 9. LWC Structure de la classe du composant JavaScript Structure des fichiers LWC vs Aura Aura Structure du controller JavaScript import { LightningElement } from "lwc"; export default class MyComponent extends LightningElement { // your code here } ({ myFunction: function(component, event, helper) { } });
  • 10. • Equivalent aux attributs sur Aura • Variables JavaScript accessibles par le template HTML à certaines conditions • Différents types de propriétés: • privée: variable seulement utilisée dans le code JavaScript • réactives: si la valeur d’une variable change, elle est mise à jour dans le template • publique: accessible par un composant parent • tracked: variable privée Propriétés LWC vs Aura
  • 11. Propriétés LWC vs Aura LWC Classe de composant JavaScript HTML Aura HTML Controller JavaScript import { LightningElement, api, track } from 'lwc'; export default class TodoItem extends LightningElement { @api itemTitle = ''; // public itemId = ''; // private @track state = { x: 100, y: 100 }; //internal & reactive } <template> <div class="view"> <label>{itemTitle}</label> </div> </template> <aura:component> <aura:attribute name="itemTitle" type="String" /> <aura:attribute name="itemId" type="String" /> <aura:attribute name="state" type="Object" /> <aura:handler name="init" action="{!c.doInit}" value="{!this}" /> <div class="view"> <label>{!v.itemTitle}</label> </div> </aura:component> ({ doInit: function(component, event, helper) { component.set("v.state", {x: 100, y: 100}); } });
  • 12. LWC Rendu conditionnel Expressions HTML LWC vs Aura Aura Rendu conditionnel <template if:true={areDetailsVisible}> <div class="slds-m-vertical_medium"> These are the details ! </div> </template> <aura:if isTrue="{!v.areDetailsVisible}"> <div class="slds-m-vertical_medium"> These are the details ! </div> </aura:if>
  • 13. LWC Iterations Expressions HTML LWC vs Aura Aura Iterations <template for:each={contacts} for:item="contact"> <li key={contact.Id}> {contact.Name}, {contact.Title} </li> </template> <aura:iteration items="{!v.contacts}" itemVar="contact"> <li key={!contact.Id}> {!contact.Name}, {!contact.Title} </li> </aura:iteration>
  • 14. Expressions complexes LWC vs Aura LWC HTML JavaScript Aura HTML <template if:false={isFirstPage}> <lightning-button-icon icon-name="utility:chevronleft" onclick={previousHandler}> </lightning-button-icon> </template> @api pageNumber; get isFirstPage() { return this.pageNumber === 1; } <aura:if isTrue="{!v.page > 1}"> <lightning:buttonIcon iconName="utility:left" variant="border" onclick="{!c.previousPage}"/> </aura:if> • Les expressions Aura avec opérations logiques sont migrées vers du code JavaScript • Utilisation de getters
  • 15. Initialisation LWC vs Aura LWC JavaScript Aura HTML JavaScript import { LightningElement } from 'lwc'; export default class MySampleInit extends LightningElement{ connectedCallback() { // initialize component } } <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> ({ doInit: function(cmp) { // initialize component } })
  • 16. Evénements personnalisés LWC vs Aura LWC JavaScript Aura HTML – Event HTML – Composant JavaScript – Composant// Creates the event with the contact ID data. const selectedEvent = new CustomEvent( 'selected’, { detail: this.contact.Id } ); // Dispatches the event. this.dispatchEvent(selectedEvent); <aura:event type="COMPONENT" description="Item selected"> <aura:attribute name="contactId" type="Id" /> </aura:event> • Utilisation des standards du web avec le constructeur CustomEvent() • Déclenchement de l’événement avec la méthode dispatchEvent() <aura:registerEvent name="itemSelected" type="c:itemSelected"/> var selectedEvent=cmp.getEvent("itemSelected"); selectedEvent.setParams({ contactId: cmp.get("v.contact").Id }); selectedEvent.fire();
  • 17. Evénements personnalisés LWC vs Aura LWC HTML Aura HTML <c-contact-list-item key={contact.Id} contact={contact} onselected={contactSelected}> </c-contact-list-item> <c:contactListItem contact="{!v.contact}" itemSelected="{!c.contactSelected}"> </c:contactListItem> • L’évenement est capté par le parent en ajoutant le préfixe « on » au nom personnalisé définit précédemment
  • 19. Wire Service – Manipulation des données Fonctionnalités spécifiques à LWC • Surcouche du Lightning Data Service déjà présent avec les composants Lightning • Permet de lire ou créer un enregistrement sans appel Apex, seulement du JavaScript • Appelable grâce à l’annotation @wire • Les références vers les objets et champs utilisés doivent être importées afin de: • empêcher la suppression de l’objet ou du champ • vérifier à l’exécution que les références existent • vérifier l’inclusion des champs et objets utilisés dans le change set • L’import des références se fait sous la forme suivante: import OBJECT_NAME from '@salesforce/schema/object'; import FIELD_NAME from '@salesforce/schema/object.field';
  • 20. Wire Service – Lecture d’un enregistrement Fonctionnalités spécifiques à LWC LWC HTML <template> <lightning-card title="My Contact Record" icon-name="standard:contact"> <template if:true={contact.data}> <div class="slds-m-around_medium"> <p>{name}</p> <p> <lightning-formatted-email value={email}> </lightning-formatted-email></p> </div> </template> </lightning-card> </template> JavaScript import { LightningElement, api, wire } from 'lwc'; import { getRecord } from 'lightning/uiRecordApi'; import NAME_FIELD from '@salesforce/schema/Contact.Name'; import EMAIL_FIELD from '@salesforce/schema/Contact.Email'; export default class GetContact extends LightningElement { @api recordId; @wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD, EMAIL_FIELD] }) contact; get name() { return this.contact.data.fields.Name.value; } get email() { return this.contact.data.fields.Email.value; } }
  • 21. Appel aux méthodes Apex Fonctionnalités spécifiques à LWC • Nécessaire seulement si le besoin n’est pas couvert par le wire service ou les composants standards tels que le Lightning Record Form ou les Lightning Record View Form et Lightning Record Edit Form • Nécessite l’import de la méthode avec la syntaxe suivante • Comme pour le framework Aura, une méthode Apex se rend disponible à l’appel grâce à l’annotation @AuraEnabled • Il est possible de lier une propriété ou méthode JavaScript à l’appel de la méthode Apex (à condition qu’elle soit définit comme cachable) avec la syntaxe suivante import apexMethodName from '@salesforce/apex/Namespace.Classname.apexMethodReference'; @wire(apexMethod, { apexMethodParams }) propertyOrFunction;
  • 22. Fonctionnalités spécifiques à LWC LWC Apex Appel aux méthodes Apex @AuraEnabled(cacheable=true) public static List<Contact> findContacts(String searchKey) { if (String.isBlank(searchKey)) { return new List<Contact>(); } String key = '%' + searchKey + '%’; return [ SELECT Id, Name, Title, Phone, Email FROM Contact WHERE Name LIKE :key ]; } JavaScript import { LightningElement, track, wire } from 'lwc'; import findContacts from '@salesforce/apex/ContactController.findContacts'; export default class ApexMet extends LightningElement { @track searchKey = ''; @wire(findContacts, { searchKey: '$searchKey' }) contacts; }
  • 23. LWC JavaScript Appel aux méthodes Apex – Méthode non cachable Fonctionnalités spécifiques à LWC import { LightningElement, track } from 'lwc'; import getContactList from '@salesforce/apex/ContactController.getContactList'; export default class ApexImperativeMethod extends LightningElement { @track contacts; @track error; handleLoad() { getContactList() .then(result => { this.contacts = result; }) .catch(error => { this.error = error; }); }
  • 24. Utilitaires JavaScript Fonctionnalités spécifiques à LWC LWC JavaScript – Utilitaire export const fireEvent = (pageRef, eventName, payload) => { if (events[eventName]) { const listeners = events[eventName]; listeners.forEach(listener => { if (samePageRef(pageRef, listener.thisArg.pageRef)) { try { listener.callback.call(listener.thisArg, payload); } catch (error) { // fail silently } } }); } }; • Partagez du code JavaScript entre composants grâce aux standards du Web JavaScript – Appel de l’utilitaire import { LightningElement, wire, track } from "lwc"; import { CurrentPageReference } from "lightning/navigation"; import { fireEvent } from "c/pubsub"; export default class UtiUse extends LightningElement { @wire(CurrentPageReference) pageRef; filter(event){ fireEvent(this.pageRef, "filterOpportunities", event.detail); } }
  • 28. LWC Résumé • Plus de JavaScript -> moins d’Apex • Standards du Web -> plus de développeurs compétents -> meilleures performances • Meilleure qualité de code -> moins de répétitions -> maintenabilité améliorée Stack Overflow Developer Survey 2019
  • 29. • Technologies fondamentalement différentes -> Analyse préalable des composants à migrer -> Refactorisation du code Apex et JavaScript • Aura et LWC peuvent cohabiter -> un composant Aura peut inclure un composant LWC • Commencer par les composants les plus simples -> composants enfants Stratégie de migration LWC
  • 30. Trailhead – Gallerie d’exemples Aller plus loin sforce.co/LWC
  • 31. Gallerie d’exemples - Dreamhouse Aller plus loin Amélioration des performances