ES6 modules in LWC
Understanding ES6 modules to write better Lighting Web Components.
We can use the concept of ES6 modules in LWC.
Modules are nothing but JavaScript files which follows specific guidelines and which has specific keywords.
A typical module is going to have three parts with in it.
1. import statements
2. Class, functions, variables, constants
3. export statement
Default Exports vs Named Exports
1. import statements
In case the code you write has some sort of dependency on other libraries or modules you need to import them first.
You can also import other JavaScript modules (or lightning web components) that you created.
2. Class, functions, variables, constants
This is the place where all the business logic gets executed.
You can have any business logic that’s as complex as making a call out to an API and fetching the information, to, business logic that just holds variables and constants.
True! A module can be as simple as having just one constant which we can import in to other module or Lightning Web Component.
Same holds true for functions too. A module can just have a function that can import on other modules.
It’s not a mandate that always web components should export classes. You can choose to export functions, variables or constants too.
3. export statement
Once we have the business logic in place we need to export it.
Once we export it that’s when other modules will be able to import it.
When we export, we can export it as default export or named export.
Per module, we can have only one default export whereas we have as many no of named exports.
It’s not a mandate that we should implement all these three steps to be considered as a module. If our code is not using other modules or libraries we can ignore the import section.
But, for sure a module should have a default export.
As wesbos quoted, ES6 modules work very much similar to a kitchen in the restaurant.
- We need to import the raw materials - import section.
- Prepare a dish - business logic and
- Hand it over, such that guests can have it - export section.