Create Lightning Web Components - 2

By in
366
Create Lightning Web Components - 2

In my previous post, we discussed the basics of creating Lightning Web Components (LWCs). Today, we will dive a little deeper and discuss how components are related to HTML and Javascript.

 

HTML & JS

An HTML file with the root tag “template” must be present for each UI component. An HTML file is not necessary for service components (libraries).

The HTML file is named using the convention <componentname>.html, for example, myComponent.html. Declaratively write the HTML for a Lightning web component inside the <template> tag. The HTML for your component is contained in the HTML template element.

 

<!– myWGComponent.html –>

<template>

<!– Replace comment with component HTML –>

</template>

 

The <template> tag is replaced with the component name, <namespace-component-name>, when a component renders. For instance, myComponent renders as <c-my-component> in the browser console, where c is the default namespace.

 

Custom element (component) tags cannot be self-closing, according to the HTML spec. Meaning that distinct closing tags are required for custom elements For instance, a separate ending </c-wg-item> tag is present in the nested <c-wg-item> component.

 

<!– myComponent.html –>

<template>

<c-wg-item></c-wg-item>

</template>

Lightning Web Components HTML Javascript
Image Source: Salesforce

Javascript

A JavaScript file is required for each component. The HTML element is defined in the JavaScript file if the component renders user interface. The JavaScript file exports functionality for use by other components if the component is a service component (library).

Lightning web components use ES6 modules in their JavaScript files. A module’s declarations are all local by default, meaning they only apply to that module.

Use the import statement to import a class, method, or variable that was declared in a module. Utilize the export statement to permit other code to use a class, method, or variable declared in a module.

The largest JavaScript file that can be used by a component is 128 KB (131,072 bytes).

The naming convention followed by the JavaScript file is <component>.js, such as myWGComponent.js.

All Lightning Web components must have a JavaScript file with at least this code.

 

import { LightningElement } from ‘lwc’;

export default class MyWGComponent extends LightningElement {

 

}

 

Conclusion

In this way, we can utilize different files like html, css and javascript to develop the front end of a lightning web component.

 

Additional Resources

Cover Photo by Pankaj Patel on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *