Modules in JavaScript | LWC
An ES6 module is a JavaScript file that exports variables or functions that other modules can use. The Primary utility of a module is to help with code reusability and code structuring.
It has two directives -
1- Export - To make variables and functions available for other scripts to use. Every module can have two different types of export, named export and default export. We can have multiple named exports per module but only one default export.
Utilities.js
export default const API_Key = '###' // only one default export per file
Utilities.js
export default const API_Key = '###'
function validateEmailAddress(email){
....
}
export {validateEmailAddress , otherVariables & functions to be exported}
2- Import - Allows to import variables and functions from a exported module.
When importing this module, named exports must be referred to by the exact same name (optionally renaming it with as), but the default export can be imported with any name
Main.js
import API_Key_Code form './utilities' // importing default export
import {validateEmailAddress as validateEmail} from './utilities' // importing named export
import * as allExportsObj from './utilities' // all exports are contained in a object named allExportsObj
Using Modules in LWC -
LWC has two patterns for sharing code -
1 - Sharing a module within a Lightning Web Component(LWC) -
In this pattern , we create a JavaScript utility file/module within a Lightning Web Component(LWC) .Other components can't use this utilities modules.
领英推荐
2 - Sharing a module across all Lightning Web Components(LWC) -
In this pattern , we create a folder/library on which we can create modules. To import the code, other components use c/componentName syntax.
Note - Components can import code only from the main JavaScript file, which has the same name as the folder name.
Some Questions on Modules in JavaScript and LWC -
LightningElement is a custom wrapper of the standard HTML element.
In order to use life cycle hooks we need to extends LightningElement class.
2. Can we use 'use strict' in a exported module?
Modules always use strict.
3. When we create new component why does it say export default
ComponentName ?
Because of export default component only we are able to embed/use one component into another.
Resources -