Modules are the mechanism available to us in Javascript in order to split the code logic into separate files. This becomes increasingly important when your codebase increases.
Possible use cases for ES6 modules:
- Widget with a lot of JS code:
Instead of including all of your Javascript inside the JS Tab of the widget creator, you can split your code into logical pieces within one or more separate files in your Widget Asset Folder and then consume those modules from the JS Tab. This will help you unclutter the JS Tab and results in a codebase that is more easily maintainable and extendible.
- Code Reuse
If you have some utility functions or custom code that you regularly copy/paste into the
JS Tab on your widgets. It makes sense to turn that common logic into modules. If you
need to make a change to that code in the future, you only have to change the module
and upload the new version to the widgets that use it. The alternative would be to
search every widget that uses it, locate the relevant code in the JS Tab and then replace
it.
- Third-party requirement
Some libraries, open-source or otherwise, only come in the form of ES6 modules.
One free benefit of using modules is you reduce the amount of JS that is loaded when you have more than one instance of the same custom widget on the same page since all widgets use the same module(s). And if you are using the same widget on different pages, on the subsequent pages, the module(s) will be loaded from the browser cache instead of downloading it again from the server.
How to Include ES6 Modules:
Modules can be imported Statically or Dynamically depending on the requirement of the code you are working with.
Static Imports:
- Using JS/CSS Includes Tab
Using the JS/CSS Include tab, you can access the option to include the js file as a
module via the include settings.
- Using the JS Tab
You can include modules in the JS tab using the import statement at the beginning of the
Editor.
Code sample for copy/paste conveniene: Click To Download
Dynamic Imports:
- Using the JS Tab
You can import modules dynamically using the Import() function.
There are 2 ways to do so. With “load as module” checked, or without.
The static way requires the ‘load as module’ at the bottom to be checked.
The dynamic way doesn’t